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.
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