Home > other >  C# InvalidArgument = Value of '2' is not valid for 'index'
C# InvalidArgument = Value of '2' is not valid for 'index'

Time:12-03

I am new to C# and I have encountered an error stating that: InvalidArgument=Value of '2' is not valid for 'index'.

I want to set the items in checkedlistbox checked if there is a match in listbox. Can anyone help me with this problem.

This the part of my code where the problems appear.

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);
     }
}

CodePudding user response:

You just need to use nested for loop. Here is the code.

 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);
     }
   }
 }

CodePudding user response:

The reason you are getting this error is because you are looping through the count of checklistbox items. So, for example if there are 3 items in that array, and listbox only has 2 items, then on the third loop (when i = 2), you are trying to reference an item in the listbox array that does not exist.

Another way to do it would be like this:

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

Update: answer updated to add MarkAsChecked() and loop through user inputted values held within checklist array.

  • Related