Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListView SelectedIndexChanged Event no Selected Items problem

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?

like image 336
Christopher Avatar asked Aug 27 '10 16:08

Christopher


2 Answers

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;
}
like image 97
Iain Ward Avatar answered Sep 29 '22 02:09

Iain Ward


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
like image 30
msergeant Avatar answered Sep 29 '22 04:09

msergeant