简体   繁体   English

选中asp:checkbox中的复选框时,不会触发OnCheckedChanged事件

[英]OnCheckedChanged event doesn't fire when check the checkbox in asp:checkbox

There is a nested repeater in my work. 我的工作中有一个嵌套的中继器 I'm responsible to add asp:checkbox on every underneath repeater item, so that we can control each item by checkbox. 我负责在每个中继器项目下面添加asp:checkbox,以便我们可以通过复选框控制每个项目。

The markup code is: 标记代码为:

<ItemTemplate>
  <li class="<%# GetCategoryClass(Container.DataItem) %> cl-li">    
    <asp:CheckBox runat="server" ID="checkBox" AutoPostBack="true" OnCheckedChanged="CheckedChanged" />
    <a class="cl-a excludeLink" visible='<%# GetCategoryClass(Container.DataItem) == "DISPLAYED" %>' href="<%# GetExcludeCategoryCommand(Container.DataItem) %>" runat="server" id="butExclude">x</a>
    <a class="cl-a" href="<%# GetCategoryCommand(Container.DataItem) %>" runat="server" id="butCategory"><%# GetCategoryTitle(Container.DataItem, true) %></a>
  </li>
</ItemTemplate>

The c# code is: C#代码是:

protected void CheckedChanged(object obj, EventArgs e)
{
    // some works    
}

I start to work on this problem and find the CheckedChanged function isn't fired via debugging. 我开始研究此问题,并发现CheckedChanged函数未通过调试触发。 But, when I add a line in 但是,当我在其中添加一行

if(IsPostBack){
   CheckedChanged(sender, e);  //add
}

It works and goes into CheckedChanged function when I debug. 当我调试时,它可以工作并进入CheckedChanged函数。 I have read many articles, none of them say I need to add that line in IsPostBack block. 我读了很多文章,没有人说我需要在IsPostBack块中添加该行。 Is there anyone can show me the principle of that? 有没有人可以向我展示这一原理?

Your code should work. 您的代码应该可以工作。 It depends how you wrote it. 这取决于您如何编写。

I made a example which works : 我举了一个可行的例子:

Default.aspx : Default.aspx

<table>
<asp:Repeater ID="RepeaterCB" runat="server">
<ItemTemplate>
     <tr>
         <td><%# Container.DataItem %></td>
         <td><asp:CheckBox runat="server" OnCheckedChanged="OnCheckedChange" AutoPostBack="true"/></td>
      </tr>
</ItemTemplate>
</asp:Repeater>
</table>

Default.aspx.cs : Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        RepeaterCB.DataSource = new List<string> { "tom", "fred", "pijule" };
        RepeaterCB.DataBind();
    }

}

protected void OnCheckedChange(object sender, EventArgs e)
{
    Response.Write("<script>alert('Fire');</script>");
}

This code fires an alert each time I check or uncheck a textbox. 每次我选中或取消选中文本框时,此代码都会触发警报。

Hope it helps. 希望能帮助到你。

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

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