6

我有一个我正在开发的小型 C# 3.5 WinForms 应用程序,它将事件日志名称从服务器抓取到列表视图中。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;

这第一次工作正常,但从第一个列表视图中第二次选择事件日志名称失败。发生的事情是 SelectedIndexChanged 事件正在获取的 SelectedItems 集合为空,因此我得到了 ArgumentOutOfRangeException。

我很茫然。关于我做错了什么或更好的方法的任何想法?

4

4 回答 4

13

是的,原因是当您选择另一个项目时,ListView 在选择新项目之前取消选择 SelectedItem,因此计数将从 1 变为 0,然后再次变为 1。修复它的一种方法是在您尝试使用它之前检查 SelectedItems 集合是否包含一个项目。你这样做的方式很好,你只需要考虑到这一点

例如

if (listView1.SelectedItems.Count == 1)
{
    string logToGet = listView1.SelectedItems[0].Text;
}
于 2010-08-27T16:48:16.613 回答
1

在尝试从中检索值之前,您应该检查 SelectedItems 集合中是否包含值。

就像是:

if(listView1.SelectedItems.Count > 0)
   //Do your stuff here
于 2010-08-27T16:49:42.913 回答
0

当您选择一个新项目时,前一个项目首先被取消选择。快速检查您的代码:

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

这将忽略所选项目更改为无所选项目。

于 2010-08-27T16:50:57.153 回答
0

我遇到了这个问题,在花了太多时间后,我意识到问题是因为试图从另一个线程获取 listView1.SelectedItems 。它可能对其他人有用。

于 2019-01-02T13:59:44.727 回答