Add Event Handler to dynamic DropDownList??????

J

JP

Add Event Handler to dynamic DropDownList

I have a page that contains dynamically generated Dropdown List controls. On
occasion, I want the dynamic dropdown list to perform an AutoPostback. Since
the control is generated programmatically, I bind an event handler to the
control before adding it to the controls collection like sew:
..
..
..
DropDownList controlDropDown = new DropDownList();
controlDropDown.ID = "drop" + drControls["controlName"].ToString();
controlDropDown.AutoPostBack = true;
controlDropDown.SelectedIndexChanged += new
EventHandler(this.controlDropDown_SelectedIndexChanged);
Page.Controls.Add(controlDropDown);
..
..
..
protected void controlDropDown_SelectedIndexChanged(object sender, EventArgs
e)
{
String a = “my answer†//my breakpoint
}

After everything is re-rendered on the post back (Yes I know you have to add
the controls back to the collection on each postback) , the postback occurs
and the controls are re-rendered, but the
controlDropDown_SelectedIndexChanged event does not fire. Why???
 
J

JP

I have solved the issue. DO NOT add the EventHandler when you create the
DropDownList for the first time. Instead add the event handler to the control
after the post back but BEFORE you add the DropDownList back to the controls
collection.

Makes since now since EventHandlers are not maintained in the Control State
or View State. Then in the event method, use the Sender object to reference
what was selected:

String myValue = ((DropDownList)sender).SelectedValue;

Maybe someone else will stumble across this post and find it helpful. It
should work for any control that allows an AutoPostback.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top