我的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>
我的代码背后
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;
}
}
}
这里的问题是,事件多次触发多少个复选框项。例如,我有两个复选框,我选中了1个复选框,然后事件被触发两次,并且相同的值被添加两次。 如果有三个复选框,则事件触发三次,如果我选择1复选框,则相同的值将被添加三次。?
答案 0 :(得分:0)
这是一个有效的例子。你可以试试这个:
这是Html代码:
<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"/>
这是C#代码:
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;
}
}
}
或使用后面的代码编辑:
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;
}
}
}