ListView SelectedIndexChanged Event no Selected Items problem

Christopher picture Christopher · Aug 27, 2010 · Viewed 18.2k times · Source

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

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

This works fine the first time, but a second selection of an event log name from the first listview fails. What is happening is the SelectedItems collection that the SelectedIndexChanged event is getting is empty so I get an ArgumentOutOfRangeException.

I am at a loss. Any ideas on what I am doing wrong or a better way to do this?

Answer

Iain Ward picture Iain Ward · Aug 27, 2010

Yes, the reason is is that when you select another item, the ListView unselects the SelectedItem before selecting the new item, so the count will go from 1 to 0 and then to 1 again. One way to fix it would be to check that the SelectedItems collection contains an item before you try and use it. The way you are doing it is fine, you just need to take this into consideration

eg

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