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?
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;
}
You should check that the SelectedItems collection has values in it before you try to retrieve values from it.
Something like:
if(listView1.SelectedItems.Count > 0)
//Do your stuff here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With