开发者

ListView SelectedIndexChanged Event no Selected Items problem

开发者 https://www.devze.com 2023-01-13 03:56 出处:网络
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 en

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 work开发者_如何学Cs 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


When you select a new item, the previous item is unselected first. Wrap your code in a quick check:

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

This will ignore selected items changing to no selected item.


I had this problem and after spending too much time I realized that the problem is because of trying to get listView1.SelectedItems from another thread. It may be useful for others.

0

精彩评论

暂无评论...
验证码 换一张
取 消