简体   繁体   English

将事件处理程序添加到动态创建的复选框(aspx,c#)

[英]adding an event handler to a dynamically created checkbox (aspx, c#)

So my problem is that I want to add an event handler to a dynamically created CheckBox. 所以我的问题是我想向动态创建的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. 我已经研究过其他方法,因此决定创建一个包含CheckBoxes的动态表对我来说是最佳选择。 I have not added these CheckBoxes to the Control Tree because I need to manage the ViewState manually. 我没有将这些CheckBox添加到“控制树”中,因为我需要手动管理ViewState。 Either way, my code works in every way except that my CheckBox's CheckChanged Event does not fire. 无论哪种方式,我的代码都能以各种方式工作,除了我的CheckBox的CheckChanged事件不会触发。 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: 我正在我的pageLoad事件中将此事件处理程序添加到我的CheckBox中,但是,我尝试的任何页面事件似乎都会给我相同的结果:

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. 我认为起初这可能是ViewState的问题,并对此进行了大量研究。 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 -罗马

为了在ASP.NET页面生命周期中正确处理动态加载的控件,需要在OnInit期间(或实际上在LoadViewState之前)将它们添加到页面中,否则它们的状态信息将不会得到维护,实际上,您可以,则视视图状态而定,具体取决于页面控制图中添加内容的方式/位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM