I have 20 iconbuttons in my form. when clickevent is performed i want to change buttons(backcolor,forecolor,Iconcolor) and remaining buttons should revert to it's default color.
public void btn1()
{
foreach (Control c in this.Controls)
{
if (c is Button)
{
(c as Button).ForeColor = Color.White;
(c as Button).BackColor = Color.FromArgb(46, 51, 73);
}
}
}
CodePudding user response:
You can make each button listen to the same Click event and do some conditional logic to achieve this.
First, make each of your buttons reference the same click event. You can do this from the Form Designer by clicking the button and in the Properties window, click the lightening bolt icon (the events icon) and change the Click event to be the method you wish:
Then, make your event method do something like this:
public void ChangeButtonColors(object sender, EventArgs e)
{
//change the color of the clicked button to desired color
Button clickedButton = (System.Windows.Forms.Button)sender;
clickedButton.BackColor = Color.Red;
//change all other buttons to defualt color
foreach (Control c in this.Controls)
{
if (c is Button && c != clickedButton)
{
c.BackColor = Color.Green;
}
}
}
This gets the type of the sender
(the clicked button in this case), and sets the BackColor
property of it. Then, the foreach
loop loops over all of the controls in the form, checks if the current item in the list is a button and is not the button that was clicked, it will change the BackColor
property. Obviously, you can change other properties of both the clicked button, and the other buttons in the foreach
.
If done properly, this is how it should behave:
CodePudding user response:
This is what RadioButton
is good for. Just set its Appearance
to Button
so it will look like a regular button but will act as a radio button: clicking it unchecks all the other buttons. The Checked
property will be true
for only the lastly clicked button: