I have a code

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

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?

2 Years
Discussion Span
Last Post by VasquezPL

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 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))
                                     .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)

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 by Fenrir()

Votes + Comments

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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.