Search code examples
c#formsloopscheckedlistbox

How to loop through checked list box you accessed through the windows controls?


I would like to loop through a checked list box and see which values are returned. That's no problem, I know I can do it with:

if(myCheckedListBox.CheckedItems.Count != 0)
{
   string s = "";
   for(int i = 0; i <= myCheckedListBox.CheckedItems.Count - 1 ; i++)
   {
      s = s + "Checked Item " + (i+1).ToString() + " = " + myCheckedListBox.CheckedItems[i].ToString() + "\n";
   }
   MessageBox.Show(s);
}

The problem is when I want to access the checked list box after I have generated it using code. I'm looping through each control in a table (on a form) and when the control is a checked list box, I need it to use the code I've written above (or similar). This is how I'm looping through the controls:

   foreach (Control c in table.Controls)
    {
        if (c is TextBox)
        {
            // Do things, that works
        }
        else if (c is CheckedListBox)
        {
            // Run the code I've written above
        }

The problem is that, when I try to access the control like this: if (c.CheckedItems.Count != 0), it doesn't even find the CheckedItems property for Control c. Is there another way I can gain access to that property of the control I've selected and am I looking at it the wrongly? Thank you in advance.

Yours sincerely,


Solution

  • You need to cast c as a CheckedListBox:

    ((CheckedListBox)c).CheckedItems;
    

    Or, you can do the following if you want to keep a reference to the correct type:

    CheckedListBox box = c as CheckedListBox;
    int count = box.CheckItems.Count;
    box.ClearSelected();
    

    If you used the first example, it would be like this:

    int count = ((CheckedListBox)c).Count;
    ((CheckedListBox)c).ClearSelected();
    

    So obviously the 2nd example is better when you require multiple operations on a cast control.

    UPDATE:

       foreach (Control c in table.Controls)
       {
          if (c is TextBox)
          {
             // Do things, that works
          }
          else if (c is CheckedListBox)
          { 
             CheckedListBox box = (CheckedListBox)c;
             // Do something with box
          }
       }