SelectedItems.Count VirtualMode 列表视图异常

SelectedItems.Count exception in listview with VirtualMode

从我的列表视图中选择一个值并单击我的按钮后,我想将我的值添加到代码中,但我的代码抛出此异常:

Count = 'this.listView1.SelectedItems.Count' threw an exception of type '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);

      }
    }

当您使用 VirutalMode 时,这是设计使然。 documentation 状态:

In virtual mode, the Items collection is disabled. Attempting to access it results in an InvalidOperationException. The same is true of the CheckedItems collection and the SelectedItems collection.

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

它继续提供以下建议:

If you want to retrieve the selected or checked items, use the SelectedIndices and CheckedIndices collections instead.

因此您应该使用 this.listView1.SelectedIndices.Count

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