简体   繁体   中英

Check box list OnSelectedIndexChanged event is firing as many times as the items are their

My HTML

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
  <ContentTemplate>
       <div id="pnlItList" runat="server">
           <asp:CheckBoxList ID="chkIt" runat="server" OnSelectedIndexChanged="chkIt_SelectedIndexChanged" AutoPostBack="true"></asp:CheckBoxList>
       </div>
  </ContentTemplate>
 </asp:UpdatePanel>

my Code behind

 protected void chkIt_SelectedIndexChanged(object sender, EventArgs e)
    {
        var d=string.Empty;
        System.Web.UI.WebControls.CheckBoxList lBox = (System.Web.UI.WebControls.CheckBoxList)sender;
        foreach (System.Web.UI.WebControls.ListItem data in lBox.Items)
        {
            if (data.Selected)
            {
                d += data.Value;
            }
        }
    }

The problem over here is how many check box items are their the event is firing that many times. For ex I am having two check boxes and I have selected 1 check box then event is firing two times and the same value is being added two times. if there are three check boxes then event is firing three times and if i select 1 check box same value is being added three times.?

Here is a working example.You can try this :

Here is Html code :

 <asp:CheckBoxList id="check1" AutoPostBack="True"
TextAlign="Right" OnSelectedIndexChanged="check1_SelectedIndexChanged"
runat="server">
<asp:ListItem>Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem>Item 4</asp:ListItem>
<asp:ListItem>Item 5</asp:ListItem>
<asp:ListItem>Item 6</asp:ListItem>
</asp:CheckBoxList>
    <br>
    <asp:label id="mess" runat="server"/>

Here is C# code:

protected void check1_SelectedIndexChanged(object sender, EventArgs e)
        {
            mess.Text = "Selected Item(s):";
            for (int i = 0; i < check1.Items.Count; i++)
            {
                if (check1.Items[i].Selected == true)
                {
                    mess.Text += check1.Items[i].Text;
                }
            }
        }

Or use the edit for your code behind :

protected void chkIt_SelectedIndexChanged(object sender, EventArgs e)
    {
        var d=string.Empty;
        for (int i = 0; i < chkIt.Items.Count; i++)
            {
                if (chkIt.Items[i].Selected == true)
                {
                    d += chkIt.Items[i].Text;
                }
            }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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