【问题标题】:Cannot access the selected items collection when the ListView is in virtual mode?ListView 处于虚拟模式时无法访问所选项目集合?
【发布时间】:2011-04-23 02:15:40
【问题描述】:

我有一个处于虚拟模式的 ListView。我想访问SelectedItems 属性。
但是当我使用 ListView1.SelectedItems 时,我收到以下异常:

Cannot access the selected items collection when the ListView is in virtual mode

如何在虚拟模式下访问ListView1.SelectedItems

【问题讨论】:

标签: c# listview selecteditem virtualmode


【解决方案1】:

这是相当老的帖子,但也许其他人会受益。

只需使用ListView.SelectedIndexCollection col = listView.SelectedIndices; 然后你可以访问一个项目:

forearch(var item in col)
{
   string txt = listView.Items[item].Text;
}

..但是您将无法使用 foreach 遍历 ListView.Items,因为在此模式下没有可用的迭代器。使用索引器就好了:-)

当你尝试使用 foreach 时,你会得到一个异常:

当 ListView 处于虚拟模式时,无法枚举 ListView 项目集合使用枚举器或调用 GetEnumerator。 改用 ListView 项目索引器并按索引访问项目 价值。

【讨论】:

    【解决方案2】:

    我将所有项目存储在列表中并使用此列表在 RetrieveVirtualItem 中提供项目 您可以找到以下选定的项目

    Dim lstData As List(Of ListViewItem) = New List(Of ListViewItem)
    Dim lstSelectedItems As List(Of ListViewItem) = lstData.FindAll(Function(lstItem As ListViewItem) lstItem.Selected = True)
    Me.Text = lstItems.Count.ToString()
    

    【讨论】:

      【解决方案3】:

      I've done it by the following code, but it has an exception when more than one item are selected:

      索引超出范围。必须是非负数且小于集合的大小。 参数名称:索引

      List<ListViewItem> ListViewItems = new List<ListViewItem>();
      
      foreach (int index in listView1.SelectedIndices)
      {
          ListViewItem SelectedListViewItem = listView1.Items[index];  // exception
          ListViewItems.RemoveAt(index);
      }
      …
      
      void listView1_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
      {
          e.Item = ListViewItems[e.ItemIndex];
      }
      

      每当您从集合中删除项目时,始终从最大索引迭代到最小索引,如下所示:

      for (int index = listView1.SelectedIndices.Count - 1; i >= 0; i--)
      {
          …
      }
      

      这是因为每次删除集合中的项目时,如果不从最大索引迭代到最小索引,索引就会发生变化。

      【讨论】:

        【解决方案4】:

        来自docs

        在虚拟模式下,Items 集合被禁用。尝试访问它会导致 InvalidOperationException。 CheckedItems 集合和 SelectedItems 集合也是如此。如果要检索选定或选中的项目,请改用 SelectedIndices 和 CheckedIndices 集合。

        【讨论】:

          猜你喜欢
          • 2014-10-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-05
          • 1970-01-01
          • 1970-01-01
          • 2020-03-01
          • 2015-06-05
          相关资源
          最近更新 更多