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

C#报错InvalidArgument: index值'2'无效,求CheckedListBox匹配勾选方案

解决CheckedListBox与ListBox匹配选中时的索引错误

你遇到的InvalidArgument=Value of '2' is not valid for 'index'错误,核心原因是代码默认CheckedListBox和ListBox的项数完全一致。当ListBox的项数比CheckedListBox少时,循环到超过ListBox项数的索引时,listbox.Items[i]会触发索引越界。

你的原代码直接用同一个索引i访问两个控件的项,这种写法仅在两个控件项数、顺序完全相同时有效,一旦项数不一致必然报错。

修复方案一:匹配所有存在的项(不依赖顺序和项数)

遍历CheckedListBox的每一项,检查ListBox中是否包含相同文本的项,存在则选中:

for (int i = 0; i < checklistbox.Items.Count; i++)
{
    string currentText = checklistbox.Items[i].ToString();
    if (listbox.Items.Contains(currentText))
    {
        checklistbox.SetItemChecked(i, true);
    }
}

如果ListBox中的项不是字符串而是自定义对象,可借助LINQ实现匹配:

using System.Linq;

// ...

for (int i = 0; i < checklistbox.Items.Count; i++)
{
    var currentItem = checklistbox.Items[i];
    if (listbox.Items.Cast<object>().Any(item => item.ToString() == currentItem.ToString()))
    {
        checklistbox.SetItemChecked(i, true);
    }
}

修复方案二:仅匹配相同位置的项(需保证顺序一致)

如果你的需求是仅匹配两个控件相同索引位置的项,需先取两个控件项数的最小值作为循环上限,避免索引越界:

int maxLoopCount = Math.Min(checklistbox.Items.Count, listbox.Items.Count);
for (int i = 0; i < maxLoopCount; i++)
{
    if (checklistbox.Items[i].ToString() == listbox.Items[i].ToString())
    {
        checklistbox.SetItemChecked(i, true);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 09:05:35