【问题标题】:Error when selecting second item from ListView C#从 ListView C# 中选择第二个项目时出错
【发布时间】:2019-10-09 14:46:49
【问题描述】:

我有一个列表视图,其中多选属性设置为 false。当用户单击它时,我获取列表视图项的 NAME 属性并将其转换为小数,然后将其提供给加载正确记录的方法。

当我选择一个项目时,无论列表中有多少项目,也不管我选择了哪个项目,下面的代码都能完美运行。

        private void ListInstruments_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListViewItem selection = listInstruments.SelectedItems[0];
            if (selection != null)
            {
                 string strSelection = selection.Name;
                 SelectedInstrumentID = Convert.ToDecimal(strSelection);
                 LoadSelectedInstrument();                
            }
        }

当我进行第二次选择(不是多选,而是从列表框中选择不同的选项)时,我收到一个引用 listInstruments.SelectedItems[0] 的错误。

System.ArgumentOutOfRangeException 消息=InvalidArgument=值 “0”对“索引”无效。参数名称:索引 Source=System.Windows.Forms

任何帮助将不胜感激。

【问题讨论】:

  • 而不是 SelectedItems[0],检查是否可以从 EventArgs e 中获取索引。像 e.Index 之类的东西还是其他东西?并在 SelectedItems[e.Index] 中使用它
  • 我要试试这个,谢谢。

标签: c# winforms listview


【解决方案1】:

有可能,没有选择任何项目,因此list.SelectedItems;您正试图从 empty 集合中获取 0th 项目,从而引发 异常。快速补丁是

 // instead of original
 // ListViewItem selection = listInstruments.SelectedItems[0];
 ListViewItem selection = list.SelectedItems.Count > 0 
   ? listInstruments.SelectedItems[0] // the collection has at least one item
   : null;                            // if the collection is empty

或者我们可以检查我们是否有选择,如果没有选择return

 private void ListInstruments_SelectedIndexChanged(object sender, EventArgs e)
 {
    if (list.SelectedItems.Count <= 0)   
        return; 

    listViewItem selection = listInstruments.SelectedItems[0];

    string strSelection = selection.Name;
    SelectedInstrumentID = Convert.ToDecimal(strSelection);
    LoadSelectedInstrument();  
 }

【讨论】:

  • 这就是我的想法,但似乎空白点击是由 is not null 检查处理的,我只是做的有点不同。我肯定是在列表视图项上进行选择。
  • 哦,等等,我明白你的意思了。因为声明失败,所以它永远不会进行空检查。
  • @Ray Delien:您正试图从 empty 集合中获取0th 项目,因为集合没有 @987654327 @th item(它是空的)你抛出了异常
  • 【不挑战只是学习】选择列表框项触发事件时,集合怎么可能是空的?
  • @Ray Delien:请注意,该事件是SelectedIndexChanged,所以当您取消选择一个项目SelectedIndex 更改时,比如说,123(之前选择的项目索引)到-1(没有选择项目)并且事件将被触发(list.SelectedItems集合为空)
猜你喜欢
  • 2023-03-25
  • 2020-04-27
  • 1970-01-01
  • 2021-05-05
  • 1970-01-01
  • 1970-01-01
  • 2011-04-11
  • 1970-01-01
  • 2013-03-21
相关资源
最近更新 更多