1
votes

I try to do somthing when the user select item in the ListView. I have tried this code:

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            q = listView1.SelectedItems[0].Index;
        }

but it doesn't work and throws an exception that says that the count of 'listView1.SelectedItems' is 0.

Why doesn't it work?

1
It is because the event is also called when nothing is selected (anymore). So you always need to check for SelectedItems.Count>0TaW
@TaW thank's. it works. write it as an answer if you want I'll accept it.Yagel
No, sorry but this is too small a problem to create an answer and let it go into the eternal SO archives.TaW
@TaW you should always use SelectedItems.Any();Mafii
They are not really different, esp, since the event is most likely caused by a (slow) user action.TaW

1 Answers

0
votes

Always check for the listview items count. If items are empty then there will be an exception.