eneskomur
eneskomur

Reputation: 91

Button BackColor doesn't change

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

Answers (2)

user153923
user153923

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

Black Frog
Black Frog

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.

enter image description here

Here is result in the Output Window:

enter image description here

Upvotes: 1

Related Questions