Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Changing button colour in c#

Status
Not open for further replies.

DESMAN2003

Programmer
Oct 27, 2003
24
AU
Hi Everyone,

today is my first day learning c# and I am having trouble creating a simple function. What I have is a button called button1 on my form. What I want is that whenever the button is clicked, the background of the button will become red. In otherwords, the button itself will become red.
This is what I have so far, but i get an error. Could anyone please help? Thanks in advance!!

private void button1_Click(object sender, System.EventArgs e)
{

If (button1.Click)
{
button1.BackColor = Color.Red;
}

}
 
you are writing what is necessary but whithout the if:
private void button1_Click(object sender, System.EventArgs e)
{
button1.BackColor = Color.Red;
 
Thanks, you are right! The only thing now is that I need to be able to make it red when I click once and then back to normal if I click again and so forth. Any ideas? Any help much appreciated!
 
Also, don't forget that it's always "if" not "If".

Always lower case.
 
hi Desman2003,

In C# you add events to f.e. a buttonclick.
a buttonclick get 2 params, object(the objects where it came from) and EventArgs (f.e. mouseclick)
if you want to check which button is pressed / clicked
you can check sender.
example:

private void ChangBackground(object sender,System.EventArgs e){
if (sender.Equals(this.button1)){
this.button1.BackColor = Color.Red;
}
}
hth's
Patrick
 
To change the color between red and default you check what color the button has and then change it to another color.

private void button1_Click(object sender, System.EventArgs e)
{
if (button1.BackColor == Color.Red)
button1.BackColor = Color.Red;
else
button1.BackColor = Color.Blue; //For exempel
}
 
...except Larsson has it backward... should be

{
if (button1.BackColor == Color.Red)
button1.BackColor = Color.Blue;
else
button1.BackColor = Color.Red;
}

...THAT will make them alternate each time you click the button.

Ben
A programmer was drowning. Lots of people watched but did nothing. They couldn't understand why he yelled "F1!"
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top