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?

Recommended Answers

All 6 Replies

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.

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

commented: Nice! +15

thx works like a charm :)

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 :(

Try this. (c as CheckedListBox).CheckedItems.Count

It works :)
thank you very much :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.