Find out if a control is a button

3

I have the following code to change the color of the buttons that are in a panel:

private void mudaCorBotao(Button bt)
{
    foreach(Control b in Panel_esq.Controls)
    {
        if (/*[O que devo colocar aqui?]*/)
        {
            b.BackColor = SystemColors.HotTrack;
            b.ForeColor = Color.White;
        }
    }
    bt.BackColor = Color.White;
    bt.ForeColor = Color.Black
}

What I'm trying to do is: When the user clicks any button on this panel, it will return all the other buttons to the default color and put the button clicked on a different color. But I have no idea what I should put inside this if .

    
asked by anonymous 23.04.2017 / 01:43

2 answers

2

Probably:

private void mudaCorBotao(Button bt) {
    foreach(Control b in Panel_esq.Controls) {
        if (b is Button) {
            b.BackColor = SystemColors.HotTrack;
            b.ForeColor = Color.White;
        }
    }
    bt.BackColor = Color.White;
    bt.ForeColor = Color.Black;
}
    
23.04.2017 / 01:56
2

Bigown's answer is right. But I would do it in a simpler way, using the method OfType from Linq.

This method filters the elements of the collection based on the type specified.

private void mudaCorBotao(Button bt)
{
    foreach(Control b in Panel_esq.Controls.OfType<Button>())
    {           
        b.BackColor = SystemColors.HotTrack;
        b.ForeColor = Color.White;            
    }

    bt.BackColor = Color.White;
    bt.ForeColor = Color.Black;
}
    
23.04.2017 / 21:05