Click here to Skip to main content
15,037,928 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
i am trying to generate selected index changed event on dynamic drop down list.code is running but event is not triggering.will deeply appreciate any help
regards,

What I have tried:

C#
DropDownList myDdl= new DropDownList();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
            {
                getDdl();
            }
myDdl.SelectedIndexChanged += new EventHandler(myDdl_SelectedIndexChanged);
}

void getDdl()
        {
           for (int i=0;i<=4;i++)
            {
                ListItem li = new ListItem("list item "+i.ToString(),i.ToString());
                myDdl.Items.Add(li);
            }
form1.Controls.Add(myDdl);
        }

protected void myDdl_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Write(myDdl.SelectedItem.Text);
                               }                
Posted
Updated 4-Nov-20 22:49pm

1 solution

When you add controls dynamically to a WebForms page, you need to recreate them every time the page is posted back. You will also need to wire up any event handlers on each request, and make sure the control is added early enough in the page lifecycle for the events to fire.
C#
protected void Page_Init(object sender, EventArgs e)
{
    getDdl();
    myDdl.SelectedIndexChanged += myDdl_SelectedIndexChanged;
}
   
Comments
Aftab Iqbal Clips 5-Nov-20 8:02am
   
tried your code bro but nothing happened issue remains the same code runs but selected index changed event not triggering can you please have a look at this once again
thanks
Aftab Iqbal Clips 5-Nov-20 9:05am
   
now its working,was not setting autopostback property to true.
akshaykokil 14-Jan-21 9:45am
   
Works correctly..Thank You!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900