Reputation: 1027
Appreciate the suggestions on the following: I have a checkboxlist called CBL_categ with over 20 items. I select some items from it, and associate this block of code below with pressing a button. The sum in the end is always zero. Why?
protected void FButton_Click(object sender, EventArgs e)
{
int sum=0;
for (int i = 1; i < 20; i++)
{
if (CBL_categ.Items[i].Selected)
sum = sum + 1;
}
statusLabel.Text += " " + sum;
}
Upvotes: 1
Views: 1145
Reputation: 2866
I wouldn't use the code you've provided. It makes the assumption that that list will always have 20 items in it. This can lead to out of bounds errors, not all items being counted, and so on. I would use something like this:
protected void FButton_Click(object sender, EventArgs e)
{
int sum=0;
foreach(ListItem item in CBL_categ.Items)
{
if(item.Selected){
sum++;
}
}
statusLabel.Text += " " + sum;
}
What it sounds like is that you are rebinding your ListBox before you actually get to this method. So, for example, if your Page_Load method looks like this:
protected void Page_Load(object sender, EventArgs e)
{
//This gets called before your event on postback and will erase your selected items.
BindListBox();
}
Does that make sense?
Edit:
If your Page_Load does look like that modify it so it looks like this to correct the problem:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack){
BindListBox();
}
}
Upvotes: 3
Reputation: 356
when you populate your checkbox list make sure that you are checking also if the page is not in post back i.e. on page_load check something like if(!Page.IsPostBack){populate your list} otherwise you will just overwrite the selections.
Upvotes: 1