Down and to the point question. I am having a miserable time with some dynamically created buttons. They do not want to fire the Click
event I have setup for them. A paraphrase of my code is below. Could anyone provide some insight as to why my dynamic controls do not work?
protected void Page_Load(object sender, EventArgs e)
{
CreateButton();
}
private void CreateButton()
{
Button btn = new Button();
btn.ID = "Button1";
btn.Click += Button1_Click;
panel1.Controls.Add(btn);
}
protected void Button1_Click(object sender, EventArgs e)
{
// Do stuff here.
// Debugger never makes it to this point.
}
I have this current functionality. It needs to be able to graphically reorder, remove and add items.
Just...don't use dynamic ASP controls. Ever. They're super hard to work with, and there are superior alternatives.
If you want to create a dynamic number of controls based on some data that you have use a Repeater
, or, if you want to create a table of data specifically, a DataGrid
. These have sensible behaviors and are far easier to work with.
If you have content that you want to optionally render, for example a single fixed button that may or may not need to be shown, then define that control in markup and use the Visible
property to determine if it is actually send to the end user.
As for why it doesn't work, ASP has many steps in a page's lifecycle. One of the early steps is to initialize it's view of the page with all of the items on it. At a later point in time the post back data is inspected, any events triggered find their corresponding control in the view of the page, and then run the corresponding handlers for that event. In your case you're creating the control and adding the handlers after the request's "page view" has already been finalized. The code didn't see your button, or any handlers for it, so it didn't have any handlers to run.
This is all complicated further if the creation of your dynamic controls are dependent on information being posted back from the user (which does in fact appear to be the case here). If you create the controls early enough in the lifecycle for them to be able to fire events, then the information that you need to get from what the user has just done hasn't yet been populated into their corresponding ASP constructs. You end up being forced to construct the dynamic objects before you actually have access to the information to construct them.