添加动态CheckBox句柄CheckedChanged事件ASP.NET
我想知道为什么事件没有触发以及如何找到触发事件的复选框控件。
chkList1 = new CheckBox(); chkList1.Text = row["subj_nme"].ToString(); chkList1.ID = row["subjid"].ToString(); chkList1.Checked = true; chkList1.Font.Name = "Verdana"; chkList1.Font.Size = 12; chkList1.AutoPostBack = true; chkList1.CheckedChanged += new EventHandler(CheckBox_CheckedChanged); Panel1.Controls.Add(chkList1); protected void CheckBox_CheckedChanged(object sender, EventArgs e) { Label1.Text = "Called"; }
如果事件没有解雇,可能是出于以下两个原因之一:
- 控件在页面生命周期中过晚地重新创建。 尝试在
OnInit
期间创建控件。 - validation阻止了回发。 要解决此问题,可以在所有CheckBox控件上将
CausesValidation
设置为false。
您可以使用sender
参数找出触发事件的控件。
protected void CheckBox_CheckChanged(object sender, EventArgs e) { //write the client id of the control that triggered the event Response.Write(((CheckBox)sender).ClientID); }