从ListView C#中选择第二项时出错

时间:2019-10-09 14:46:49

标签: c# winforms listview

我有一个将multiselect属性设置为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 Message = InvalidArgument =值   '0'对'index'无效。参数名称:索引   Source = System.Windows.Forms

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

有可能没有选择任何项目,因此list.SelectedItems是空的。您正试图从 empty 集合中获得第0个项目,因此抛出了 exception 。快速补丁是

 // 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();  
 }