Reputation: 91
I want to change my button's color when it has a default color. I tried with code that in below but it doesn't work. How can I do that?
public void ClickedButton (object sender, EventArgs e)
{
if ((sender as Button).BackColor == System.Drawing.SystemColors.Control) {
(sender as Button).BackColor = Color.Turquoise;
}
}
Upvotes: 0
Views: 1146
Reputation:
Try casting the sender to a Button first:
public void ClickedButton (object sender, EventArgs e)
{
var btn = sender as Button;
if ((btn != null) && btn.BackColor == System.Drawing.SystemColors.Control)) {
btn.BackColor = Color.Turquoise;
}
}
If this is a Windows Form control, that should work.
If this is a Web Form control, it may not (unless you are calling it as part of a postback).
Upvotes: 0
Reputation: 11703
You need to add debug line to verify the current color of the button
public void ClickedButton (object sender, EventArgs e)
{
// add debug line here
string message = (sender as Button).BackColor.ToString();
Debug.WriteLine(message);
if ((sender as Button).BackColor == System.Drawing.SystemColors.Control) {
(sender as Button).BackColor = Color.Turquoise;
}
}
That will help with your troubleshooting of code. Also there is nothing wrong with your current code. Below is the result.
Here is result in the Output Window:
Upvotes: 1