Select selected item in ASP.NET CheckBoxList

I have a CheckBoxList with the SelectedIndexChanged event, where I add the value of the selected ListItem to the variable. I want to subtract the value when the item is not checked.

I tried SelectedIndex, but returns -1, and SelectedItem returns null. And the EventArgs argument contains no data to help ...

-1
source share
1 answer

You must use the Items property. In other words, your variable should begin with its value set to everything that should be before applying the selected elements. Then iterate over the elements, applying your logic to the variable, one element for each selected element. Then, no matter which user selects or deselects, you will always get the correct value for your variable.

int myValue = 0;

foreach(ListItem item in cbl.Items)
{
    if(item.Selected) myValue += int.Parse(item.Value);
}
0
source

All Articles