Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all controls of a specific type

Tags:

c#

.net

winforms

I have multiple pictureboxes and I need to load random images into them during runtime. So I thought it would be nice to have a collection of all pictureboxes and then assign images to them using a simple loop. But how should I do it? Or maybe are there any other better solutions to such problem?

like image 539
drv Avatar asked Jan 07 '11 21:01

drv


3 Answers

Using a bit of LINQ:

foreach(var pb in this.Controls.OfType<PictureBox>())
{
  //do stuff
}

However, this will only take care of PictureBoxes in the main container.

like image 89
Femaref Avatar answered Nov 11 '22 07:11

Femaref


You could use this method:

public static IEnumerable<T> GetControlsOfType<T>(Control root)
    where T : Control
{
    var t = root as T;
    if (t != null)
        yield return t;

    var container = root as ContainerControl;
    if (container != null)
        foreach (Control c in container.Controls)
            foreach (var i in GetControlsOfType<T>(c))
                yield return i;
}

Then you could do something like this:

foreach (var pictureBox in GetControlsOfType<PictureBox>(theForm)) {
    // ...
}
like image 37
cdhowie Avatar answered Nov 11 '22 08:11

cdhowie


If you're at least on .NET 3.5 then you have LINQ, which means that since ControlCollection implements IEnumerable you can just do:

var pictureBoxes = Controls.OfType<PictureBox>();
like image 9
Dan Tao Avatar answered Nov 11 '22 07:11

Dan Tao