Richard Jacobs Richard Jacobs - 1 month ago 6
C# Question

C# Removing all the images in a control group

I don't get an option

.Image
when I apply this code:

foreach(Control b in _SelectionPanel.Controls)
{
if (b is Button)
{
b.Image = null;
}
}


However, I can get the option 'Visible':

foreach(Control b in _SelectionPanel.Controls)
{
if (b is Button)
{
b.Visible = false;
}
}


I'm trying to remove all the images from the buttons in a control group. Any ideas?

Answer

is only checks if the type is Button.

You want to use as to perform the actual cast, hence allowing you to access Button's properties. If the cast is invalid, you will simply get a null reference, so simply perform the as cast, then check if your variable is null before using it.

foreach(Control b in _SelectionPanel.Controls)
{
    Button castB = b as Button;
    if (castB != null)
    {
        castB.Image = null;
    } 
}
Comments