【问题标题】:SelectedItems.Count exception in listview with VirtualMode具有 VirtualMode 的列表视图中的 SelectedItems.Count 异常
【发布时间】:2021-10-26 16:25:17
【问题描述】:

从我的列表视图中选择一个值并单击我的按钮后,我想将我的值放入代码中,但我的代码抛出了这个异常:

Count = 'this.listView1.SelectedItems.Count' 引发了“System.InvalidOperationException”类型的异常

private void OK_button_Click(object sender, EventArgs e)
    {
      try
      {
        // OK -> Daten übernehmen
        ListView.SelectedListViewItemCollection data = this.listView1.SelectedItems;

        int iCount = data.Count;
        if (iCount != 1)
        {
          MessageBox.Show("Value is empty");
          return;
        }
        DialogResult = DialogResult.OK;
        Close();
      }
      catch (Exception ex)
      {
        //WriteProtokoll(ex.ToString(), 0);   
        Close();
      }
    }
  } 
 private void listView1_SearchForVirtualItem(object sender, SearchForVirtualItemEventArgs e)
    {
      e.Index = Array.FindIndex(myData, s => s == textBox1.Text.ToString());
    }

    private void listView1_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
    {

      e.Item = new ListViewItem(myData[e.ItemIndex]);
     
    }
    myData = new string[dataListSize];
      for (int i = 0; i < dataListSize; i++)
      {
        myData[i] = String.Format("{0}", i);
      }


 private void textBox1_TextChanged(object sender, EventArgs e)
    {

      String MyString = textBox1.Text.ToString();  

      ListViewItem lvi = listView1.FindItemWithText(MyString.TrimEnd());
      //Select the item found and scroll it into view.
      if (lvi != null)
      {
        listView1.SelectedIndices.Clear();
        listView1.SelectedIndices.Add(lvi.Index);
        listView1.EnsureVisible(lvi.Index);

      }
    }

【问题讨论】:

  • Why the Items of a Virtual ListView that are not visible don't have index? -- 查看注释、RetrieveVirtualItemSearchForVirtualItem 处理程序以及在 virtual 列表中搜索项目的代码 (FindItemWithText()) .
  • @Jimi 在我的列表视图中选择我的值后,我仍然无法获得我的值,我的 RetrieveVirtualItemSearchForVirtualItem 处理程序工作正常,但在我选择了值之后并单击 OK 我无法将其保存为值以在我的代码中进一步使用它。
  • @Ahmet 该问题似乎与您在此问题中提出的问题无关。也许您想在网站上提出一个新问题?

标签: c# winforms listview


【解决方案1】:

这是您使用VirutalMode 时的设计。 documentation 声明:

在虚拟模式下,Items 集合被禁用。 尝试访问它会导致 InvalidOperationException。 CheckedItems 集合和SelectedItems 集合也是如此。

我们可以在source code 中确认这一点。

它继续提供以下建议:

如果要检索选定或选中的项目,请改用 SelectedIndices 和 CheckedIndices 集合。

因此,您应该改用this.listView1.SelectedIndices.Count

再看source code,我们可以看到这不会抛出异常。

【讨论】:

  • @LIama 感谢这工作,但仍然无法在我的 OK_button_Click 中获取我的值 不能使用 List.FindIndex() FindItem() 或 listView1.FindItemWithText() 可能我很愚蠢
  • 我的文本框 textBox1_TextChanged ** 调用我的 **SearchforItem:但我的 OK_Button_click 对用户 FindItemWithText 没有参数
  • @Ahmet 因为它解决了您的问题,请随时将我的答案标记为已接受。
猜你喜欢
  • 1970-01-01
  • 2014-05-19
  • 1970-01-01
  • 2015-04-11
  • 2011-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多