【问题标题】:Adding a CheckChanged event handler to CheckBox inside a dynamically added UserControl将 CheckChanged 事件处理程序添加到动态添加的 UserControl 内的 CheckBox
【发布时间】:2009-09-30 20:23:49
【问题描述】:

我有一个包含 CheckBox 和 TextBox 的 UserControl:

<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 中放置一个断点时,当我的复选框被点击时它永远不会被命中。

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

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

所以,当我添加事件处理程序时,它似乎没有启动。这很奇怪,因为它会拾取其他所有内容。

我错过了什么吗?

【问题讨论】:

    标签: c# asp.net user-controls event-handling


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      如果您希望在单击复选框时触发事件,您还需要在复选框上设置 AutoPostBack = true。如果将光标放在文本框中并按回车键(导致回发),事件会触发吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-04
        • 2011-08-11
        • 2014-07-06
        • 2016-06-06
        • 2018-04-23
        相关资源
        最近更新 更多