ListView error SelectedIndexChanged without selected items

I have a small C # 3.5 WinForms application that I am working on that grabs the names of event logs from the server into a list. When one of these items is selected, the other listview is populated with event log entries from the selected event log using the SelectedIndexChanged event, capturing the text property of the 1st item in the SelectedItems collection, as shown below.

string logToGet = listView1.SelectedItems[0].Text;

This works fine for the first time, but the second selection of the event log name from the first list does not work. It happens that the SelectedItems collection that the SelectedIndexChanged event receives is empty, so I get an ArgumentOutOfRangeException.

I'm at a loss. Any ideas on what I'm doing wrong or the best way to do this?

+5
source share
3 answers

Yes, the reason is that when you select another item, the ListView deselects SelectedItem before selecting a new item, so the counter will go from 1 to 0, and then back to 1. One way to fix this is to check that the SelectedItems collection contains item before trying to use it. The way you do it is great, you just need to take that into account

eg,

if (listView1.SelectedItems.Count == 1)
{
    string logToGet = listView1.SelectedItems[0].Text;
}
+12
source

You must ensure that there are values ​​in the SelectedItems collection before trying to extract values ​​from it.

Sort of:

if(listView1.SelectedItems.Count > 0)
   //Do your stuff here
+1
source

, . :

if( listView1.SelectedItems.Count > 0)
{
 string logToGet = listView1.SelectedItems[0].Text;
}

, .

0

All Articles