gpt4 book ai didi

c# - 将 CheckChanged 事件处理程序添加到动态添加的 UserControl 中的 CheckBox

转载 作者:行者123 更新时间:2023-11-30 22:48:47 24 4
gpt4 key购买 nike

我有一个包含复选框和文本框的用户控件:

<asp:CheckBox runat="server" ID="chk1" />
<asp:TextBox runat="server" ID="tb1" />

在 Page_Load 上,我将其中的几个动态添加到页面上的面板中:

 //loop through the results from DB
foreach (Thing t in Things)
{
//get the user control
MyUserControl c1 = (MyUserControl )Page.LoadControl("~/UserControls/MyUserControl.ascx");

//set IDs using public properties
c1.ID = "uc" + t.ID;
c1.CheckBoxID = "chk" + t.ID;
cl.TextBoxID = "tb" + t.ID;

//add it to the panel
myPanel.Controls.Add(c1);

//add the event handler to the checkbox
((CheckBox)myPanel.FindControl(c1.ID).FindControl(c1.CheckBoxID)).CheckedChanged += new EventHandler(CheckBox_CheckedChanged);
}

然后我在同一页面中为事件处理程序创建了方法:

protected void CheckBox_CheckedChanged(object sender, EventArgs e)
{
string test = "breakpoint here";
}

当我在 CheckBox_CheckedChanged 中放置一个断点时,当我的复选框被点击时它永远不会命中。

当我查看 View 源代码时,这是生成的代码:

<input id="ctl00_body_uc1_chk1" type="checkbox" name="ctl00$body$uc1$chk1" checked="checked" />

所以,当我添加事件处理程序时,它似乎没有启动。这很奇怪,因为它会吸收其他所有东西。

我错过了什么吗?

最佳答案

添加CheckBox.AutoPostBack属性并将其设置为“true”。

CheckBox cb = ((CheckBox)myPanel.FindControl(c1.ID).FindControl(c1.CheckBoxID));
if(cb != null)
{
cb.AutoPostBack = true;
}

关于c# - 将 CheckChanged 事件处理程序添加到动态添加的 UserControl 中的 CheckBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1500450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com