Find out if particular control is a button

Asked

Viewed 154 times

3

I have the following code that serves 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 on any button on that panel, it will return all the other buttons to the default color and place the button clicked on a different color. But I have no idea what I should put inside this if.

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;
}

I put in the Github for future reference.

  • I did not know that there was this "is" no if! I paid a lot of dick already in situations that this "is" would help a lot. Thanks.

2

The response of Maniero is right. But I would do it in a simpler way, using the method OfType linq.

This method filters the collection elements 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;
}
  • Thank you jbueno. I want to start to dominate Linq in the future. But at the moment I’m running out of time. But it’s already good to acquire a knowledge like what you’ve been through.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.