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();
}
}
}
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.
Try using:
Also, this will only show the last item selected. If you have multiples selected, you will have to concatenate all and then assign to TextBox1.Text. Or use this:
Instead of using
TextBox1.Text = Chosen[i].ToString();
useThe problem is that when you use foreach, the value of i is actually a value of the actual element of the Chosen list, not an index.
The way you wrote is working well in a for loop:
Is this what you need?
In this case you don't need Chosen, but if you still need to populate it, you dont need foreach loop
Suppose this is your CheckBoxList
The Code behind event: Edited
This does what you have explained as per my understanding
Edited and Tested