I have a code

foreach(Control grpbox in this.Controls)
{
     if (tb is CheckedListBox)
     {
         tb.CheckedItems...
     }
}

and I need to use tb.CheckedItems as above...but somehow CheckedItems is not visible there...
I can see other things related to "Control" but not related to "checklistbox"

how to fix that?

If the control is in a group box or panel, you need to search there for it. Think of it as searching for a file you stored in a directory "c:\temp". If you only search in "c:\" you won't find it, you need to look in "c:\temp". Likewise, group boxes and panels are containers.

Edited 2 Years Ago by cgeier

Can't quite remember where i found this but it works like a charm.

Add the following method in your application

public IEnumerable<T> FindControls<T>(Control control) where T : Control
{
  var controls = control.Controls.Cast<Control>();

  return controls.SelectMany(ctrl => FindControls<T>(ctrl))
                                     .Concat(controls)
                                     .Where(c => c.GetType() == typeof(T)).Cast<T>();
}

Then you can call it as followed.

var t = FindControls<CheckedListBox>(this);

foreach(Control c in t)
{
  MessageBox.Show(c.Name);
}

This will for example bring back all the checklistboxes on the control you called the method with. Above the form is being passed in. this

Edited 2 Years Ago by Fenrir()

Comments
Nice!

The problem is that I still cannot use that way I want - for example

 var t = FindControls<CheckedListBox>(this);

            foreach (Control c in t)
            {
                if (c.Enabled == true && c.CheckedItems.Count > 0)
                {
                    do sth
                }
            }

CheckedItems.Count does not exist for c :( and I dunno how to fix that :(

This question has already been answered. Start a new discussion instead.