C#的CheckBoxList [英] C# Checkboxlist
问题描述
好了,所以我有n复选框复选框列表。每次我检查框我要被添加到列表()选定该号码。如果没有选中该复选框我想从列表中删除。然后,当我打一个按钮,我想显示一个文本框列表中。这里是我的code:
Ok so I have a checkbox list with n checkboxes. Everytime I check a box I want that number to get added to a list (Chosen). When the box is unchecked I want to remove it from the list. Then when I hit a button I want to display the list in a textbox. Here is my code:
public partial class _Default : System.Web.UI.Page
{
List<int> Chosen = new List<int>();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Chosen"] == null)
{
Session["Chosen"] = new List<int>();
}
Chosen = (List<int>)Session["Chosen"];
for (int i = 0; i < Numbers.Items.Count; i++)
{
if (Numbers.Items[i].Selected) { Chosen.Add(i + 1); }
else { Chosen.Remove(i + 1); }
}
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (var i in Chosen)
{
TextBox1.Text = Chosen[i].ToString();
}
}
}
不用说,这是行不通的,我希望它的方式。当我选择1和点击按钮将其写入1入禁区,但如果我不选择它,并按下按钮离开那里1。另外,如果我选择任意数量的1以外我得到这一行的错误:
Needless to say it does not work the way I want it to. When I select 1 and hit the button it writes 1 into the box, but if I unselect it and hit the button it leaves 1 there. Also if I select any number other than 1 I get an error on this line:
TextBox1.Text = Chosen[i].ToString();
话说索引超出范围。然而,当我调试数字似乎正确分配到列表中。
Saying index is out of range. Yet when I debug the numbers seem to be allocating to the list properly.
推荐答案
这是你需要什么?
<asp:TextBox ID="textBox1" runat="server">
</asp:TextBox>
<asp:CheckBoxList ID="Numbers" runat="server"
OnSelectedIndexChanged="UpdateCheckBoxex" AutoPostBack="true">
<asp:ListItem Text="One" Value="One" />
<asp:ListItem Text="Two" Value="Two" />
<asp:ListItem Text="Three" Value="Three" />
<asp:ListItem Text="Four" Value="Four" />
</asp:CheckBoxList>
protected void UpdateCheckBoxex(object sender, EventArgs e)
{
string s = string.Empty;
new List<ListItem>(Numbers.Items.Cast<ListItem>().Where(i => i.Selected)).ForEach(x => s += string.Format("{0}, ", x.Text));
textBox1.Text = s;
}
在这种情况下,你不需要选择,当然,如果你仍然需要填充它,你不需要foreach循环
In this case you don't need Chosen, but if you still need to populate it, you dont need foreach loop
List<int> Chosen = new List<int>();
Chosen.AddRange(Numbers.Items.Cast<ListItem>().Where(i => i.Selected).Select(x => Numbers.Items.IndexOf(x) + 1));
这篇关于C#的CheckBoxList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!