Checking the list
6 answers
To remove multiple elements, you need to parse the elements in reverse order.
protected void removeButton_Click(object sender, EventArgs e)
{
for (int i = listBox.Items.Count - 1; i >= 0; i--)
listBox.Items.RemoveAt(i);
}
If you disassemble it as usual, the result will be quite unexpected. Example: If you delete item 0, then item 1 becomes the new item 0. If you now try to delete what you think is item 1, you are effectively deleting what you see as item 2.
+1
source to share
You might want to go with an early breakout based on your problem and that ListBox.SelectedIndex will return -1 if nothing is selected .
to borrow some tvanfosson event handler code.
protected void removeButton_Click( object sender, EventArgs e )
{
if (listBox.SelectedIndex < 0) { return; }
// do whatever you wish to here to remove the list item
}
0
source to share