You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ListView开启VirtualMode时访问SelectedItems.Count抛出InvalidOperationException异常如何解决

异常原因

当ListView控件开启VirtualMode = true进入虚拟模式时,控件不会在内存中维护完整的ListViewItem对象集合,所有可见项都是通过RetrieveVirtualItem事件按需动态生成的。
微软官方对虚拟模式下的ListView有明确限制:禁止访问SelectedItems属性,直接调用该属性获取选中项集合时,就会抛出你遇到的System.InvalidOperationException异常:

Count = 'this.listView1.SelectedItems.Count' 抛出了类型为'System.InvalidOperationException'的异常

修复方案

虚拟模式下要获取选中项,应该使用SelectedIndices属性,该属性在虚拟模式下可正常使用,存储了所有选中项对应的索引,你可以直接通过索引从自己维护的数据源myData中读取选中值即可。
修改后的确认按钮点击事件代码如下:

private void OK_button_Click(object sender, EventArgs e)
{
    try
    {
        // 虚拟模式下用SelectedIndices替代SelectedItems
        ListView.SelectedIndexCollection selectedIndices = this.listView1.SelectedIndices;
        int iCount = selectedIndices.Count;
        if (iCount != 1)
        {
            MessageBox.Show("Value is empty");
            return;
        }
        // 直接从自定义数据源取选中值
        int selectIndex = selectedIndices[0];
        string selectValue = myData[selectIndex];
        // 此处可添加对selectValue的后续业务处理逻辑

        DialogResult = DialogResult.OK;
        Close();
    }
    catch (Exception ex)
    {
        //WriteProtokoll(ex.ToString(), 0);   
        Close();
    }
}

额外注意事项

你现有的SearchForVirtualItem事件逻辑是正确的,Array.FindIndex找不到匹配项时会返回-1,刚好符合ListView虚拟模式的要求,不需要额外修改。后续所有需要操作ListView项的场景,都不要直接访问Items、SelectedItems等内置集合,全部通过索引操作自己维护的数据源即可。

内容的提问来源于stack exchange,提问作者liberty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 09:30:05