KOMAEI
KOMAEI

Reputation: 31

Reading controls in a panel

I have the following code to read all the items of some checkedlistbox objects in a panel. There are also some other controls such as labels in this panel.After reading some items correctly,I am featuring an error. Can you please help me how to correct the code: Thanks a lot in advanced.

    foreach (CheckedListBox chb in PanelControls.Controls)
    {
        foreach (var itm in chb.Items)
        {
            MessageBox.Show(itm.ToString());
        }
    }

error: Unable to cast object of type 'System.Windows.Forms.Label' to type 'System.Windows.Forms.CheckedListBox

Upvotes: 0

Views: 58

Answers (2)

Andrew Backes
Andrew Backes

Reputation: 1904

You need to make sure the current control is actually a CheckListBox.

Something like this would suffice:

foreach (Control c in PanelControls.Controls) 
{ 
  if (c is CheckListBox) 
  { 
   // Do your actions
  }
}

Or something likes this might help you as well:

foreach (var control in PanelControls.Controls.OfType<CheckListBox>())
{
   ...
}

You are now only looping through controls that are actually a CheckListBox.

Upvotes: 0

Darren Young
Darren Young

Reputation: 11100

Use

PanelControls.Controls.OfType<CheckedListBox>()

Upvotes: 1

Related Questions