Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I try to make a usercontrol with lets say 24 buttons, one button for every hour of a day. If a user clicks on a button it should change its color and I would like to get the name of the specific button. I would like to use one onclick event that calls the same function for all buttons (writing 24 times the same could doesn't seem efficient).Now my problem is (beside lack of knowledge) that currently if I create the control and click one button it calls the following event:

C#
public void single_button_Click(object sender, EventArgs e)
        {
            if (BackColor == Color.Red)
            {
                BackColor = SystemColors.Control;
            }
            if (BackColor == SystemColors.Control)
            {
                BackColor = Color.Red;
            }
        }


But this changes the background of the control, not of clicked button.
I could make a function for each button and use btn1.BackColor for example, but that would be inefficient (24 times the same code).
How can I solve this?
Additionaly I would like to get the name or text of the button that was clicked, how can I achieve that in a generic function?
Thanks for you help!
Posted
Updated 18-May-10 21:31pm
v2

You need to identify which button sent the message in order to change the colour of only that button. You do that by casting the sender parameter to Button, something like:
C#
public void single_button_Click(object sender, EventArgs e)
{
  Button btn = (Button)sender;
  if (btn.BackColor == Color.Red)
  {
    btn.BackColor = SystemColors.Control;
  }
  else if (btn.BackColor == SystemColors.Control)
  {
    btn.BackColor = Color.Red;
  }
}
 
Share this answer
 
Comments
DaveAuld 19-May-10 9:40am    
This doesn't change the color of the other buttons, hence the approach i used.
Good point though, i never explained about casting the Object to the Button or Control.....
Here is the code i just knocked up for doing this.

In my example i have a panel on the form which contains the buttons.

All the buttons.Click events point to the same click function;

C#
private void button_Click(object sender, EventArgs e)
{

    //set all the controls in the panel to the same backcolor
    foreach (Control c in panel1.Controls)
    {
        c.BackColor = Color.DimGray;
    }
    //set the clicked control to a different color
    Control o = (Control)sender;
    o.BackColor = Color.Green;
}


When a button is clicked, all the buttons are reset to the same color, then the button that was clicked has its colour changed.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900