views:

399

answers:

1

Dear reader,

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,

+2  A: 

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
      }
   }
GenericTypeTea
Thank you for your response, but where do I put that?
Kevin van Zanten
@Kevin - updated.
GenericTypeTea
That second one does indeed work, but I'm not sure how or where to use the first one. Nonetheless, it works. Thank you!
Kevin van Zanten
@Kevin - what do you mean? Look, if you have a control that is a CheckedListBox, all you have to do is cast it to a CheckedListBox and you can access the CheckedListBox properties?
GenericTypeTea
I tried: `if ((CheckedListBox)c.CheckedItems.Count != 0)`, but I get the same problem as before. Casting it doesn't let me access the property. `c as CheckedListBox` (your `box` example) works fine, however. Am I doing something wrong here?
Kevin van Zanten
Yes, you're doing it wrong. It should be: `if (((CheckedListBox)c).CheckedItems.Count != 0)`.
GenericTypeTea
I see where I went wrong now, both of your solutions work fine now. Thank you again.
Kevin van Zanten