This works fine:
private void btnDelete_Click(object sender, EventArgs e)
{
for (int i = 0; i < listBox1.SelectedItems.Count; i++)
{
listBox1.Items.Remove(listBox1.SelectedItems[i].ToString());
i--;
}
}
But this doesn’t work:
private void btnDelete_Click(object sender, EventArgs e)
{
listBox1.Items.Remove(listBox1.SelectedItems);
}
Why is the second btnDelete_Click not working? I mean I select a line on my listBox1 with my mouse and then press the button.
Doesn’t the .Remove function recognize which line I selected? Even though I say .Remove(listBox1.SelectedItem), is it a must to have and selectedItem array? Isn’t the word SelectedItems self-explanatory? And since I clicked the line on my listBox1 with my mouse, can’t the program or the IDE understand which line is selected? Why do I still have to use SelectedItems[i]?
The reason the second example does not work is because you are trying to pass multiple items in the form of a collection to be removed at once.
To remove an item you need to do it one at a time, hence why you need a loop.
Also, might I suggest using a
ListViewinstead? I personally find them easier to use with many more options.For example you could make your loop for a
ListViewwith just thisIf you are trying to remove only one item at a time that is selected then you do
SelectedItemrather thanSelectedItems, plural being the collection that it can’t handle without a loop, singular being a single item that it can understand.