Dynamic controls and events

By steve, 8 June, 2011

I am having a problem where certain dynamic controls are not having their events triggered. I can re-create the problem by getting my code to re-create the controls in the PreRender event as follows:

protected void Page_PreRenderobject sender, EventArgs e)
{
GenControls();
}

protected void Page_Load(object sender, EventArgs e)
{
GenControls();
}

public void GenControls()
{
Button b1 = new Button();
b1.Text = "Add";
b1.CommandArgument = arg;
b1.Click += new EventHandler(b1_Click);

OptionCell.Controls.Add(b1);
}

private void b1_Click(object sender, EventArgs e)
{
if (sender.GetType().ToString().CompareTo("System.Web.UI.WebControls.Button") != 0)
{
throw new Exception("The AddMultiControl_Click() function can only be called by a button");
}

Button b1 = (Button)sender;

..... Process input ......

GenControls();
}

If I remove the Page_PreRender function, the button works on the first load of the page, nut not immediately after a successful trigger of the b1_Click event.

I will update once I have a solution, but the other interesting thing is that other buttons that get a different function continue to work correctly in all circumstances, and these buttons are created in the same way.

Solution
I added the following code to the GenControls function:

b1.ID = "Add_New_Type_" + controlID;

This gives the button a consistent identifier, which seems to fix the problem (possibly because when the button is re-created, the event is already set up to trigger with the same identifier).

Update
You will also have problems firing events if the button's ID has a ":" in it.

Update 2
If you are using a drop-down list, you need to add the control to the page before you add any items to the drop-down list if you want to be able to fire an event from your control.

Tags

Comments