问题
So my problem is that I want to add an event handler to a dynamically created CheckBox. I have already looked at other ways to do this, and decided that creating a dynamic table which contains my CheckBoxes is the best option for me. I have not added these CheckBoxes to the Control Tree because I need to manage the ViewState manually. Either way, my code works in every way except that my CheckBox's CheckChanged Event does not fire. I am adding this eventhandler to my CheckBox in my pageLoad event, however, any page event I try seems to give me the same results:
CheckBox chbxLv1 = new CheckBox();
chbxLv1.ID = "DymanicallyCreatedIDForIdentification";
chbxLv1.AutoPostBack = true;
chbxLv1.CheckedChanged += new EventHandler(this.checkChanged);
/* Way lower in my code */
protected void checkChanged(object sender, EventArgs e)
{
//Some code goes here which never seems to execute... grrr
}
I thought that this may be a problem with the ViewState at first and did quite a bit of research on that. I'm now thinking I am doing something dumb with adding an event handler. I'm not sure why this event never fires, but I'm a little new at adding events to a control. Do I need a delegate here?
--Roman
回答1:
In order for dynamically loaded controls to be handled properly during the ASP.NET Page Lifecycle, they need to be added to the page during OnInit (or prior to LoadViewState, really) otherwise their state information will not be maintained and you can, in fact, corrupt the viewstate depending on how/where things are added in the page's control graph.
来源:https://stackoverflow.com/questions/8001213/adding-an-event-handler-to-a-dynamically-created-checkbox-aspx-c