繁体   English   中英

C# InvalidArgument = '2' 的值对于 'index' 无效

[英]C# InvalidArgument = Value of '2' is not valid for 'index'

我是 C# 的新手,我遇到了一个错误,指出:InvalidArgument='2' 的值对 'index' 无效。

如果列表框中有匹配项,我想设置检查列表框中的项目。 谁能帮我解决这个问题。

这是我的代码中出现问题的部分。

for (int i = 0; i < checklistbox.Items.Count; i++)
{
    if (checklistbox.Items[i].ToString() == listbox.Items[i].ToString())
     {
        //Check only if they match! 
        checklistbox.SetItemChecked(i, true);
     }
}

您收到此错误的原因是因为您正在循环检查清单框项目的计数。 因此,例如,如果该数组中有 3 个项目,而列表框只有 2 个项目,那么在第三个循环中(当 i = 2 时),您将尝试引用列表框数组中不存在的项目。

另一种方法是这样的:

foreach (var item in listbox.Items)
        {
            if (Array.Exists(checklistbox.Items, lbitem => lbitem.ToString() == item.ToString()))
            {
               //They match! 
               checklistbox[item].MarkAsChecked()
            }
        }

更新:更新答案以添加 MarkAsChecked() 并循环遍历清单数组中保存的用户输入值。

您只需要使用嵌套的 for 循环。 这是代码。

 for (int i = 0; i < listbox.Items.Count; i++)
 {
   for (int j = 0; j < checkedlistbox.Items.Count; j++)
   {
     if (listbox.Items[i].ToString() == checkedlistbox.Items[j].ToString())
     {
       //Check only if they match! 
       checkedlistbox.SetItemChecked(i, true);
     }
   }
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM