ListView SelectedIndexChanged事件没有选定的项目问题
我正在开发一个小型 C# 3.5 WinForms 应用程序,它将事件日志名称从服务器抓取到列表视图中。当选择其中一个项目时,另一个列表视图将使用 SelectedIndexChanged 事件通过抓取 SelectedItems 集合中第一个项目的文本属性来填充所选事件日志中的事件日志条目,如下所示。
string logToGet = listView1.SelectedItems[0].Text;
第一次可以正常工作,但从第一个列表视图中第二次选择事件日志名称会失败。发生的情况是 SelectedIndexChanged 事件获取的 SelectedItems 集合为空,因此我收到 ArgumentOutOfRangeException。
我不知所措。关于我做错了什么或更好的方法有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,原因是当您选择另一个项目时,ListView 在选择新项目之前会取消选择 SelectedItem,因此计数将从 1 变为 0,然后再次变为 1。解决此问题的一种方法是在尝试使用 SelectedItems 集合之前检查它是否包含某个项目。你这样做的方式很好,你只需要考虑到这一点,
例如
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
在尝试从 SelectedItems 集合中检索值之前,您应该检查其中是否包含值。
像这样的东西:
You should check that the SelectedItems collection has values in it before you try to retrieve values from it.
Something like:
当您选择一个新项目时,将首先取消选择前一个项目。将代码包装在快速检查中:
这将忽略选定的项目更改为无选定的项目。
When you select a new item, the previous item is unselected first. Wrap your code in a quick check:
This will ignore selected items changing to no selected item.
我遇到了这个问题,花了太多时间后我意识到问题是因为试图从另一个线程获取 listView1.SelectedItems 。它可能对其他人有用。
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.