Change backcolor according to color selected from combobox

600 views Asked by At

In my form I have a combobox. It has color names like Red, Yellow, etc.

I want to change backcolor for my form to match the color selected from combobox when I click a button. So far I have this:

private void button_Pass_Click(object sender, EventArgs e)
{
    if (comboBox_color.SelectedText == "Red")
    {
        this.BackColor = System.Drawing.Color.Red;
    }
    else if (comboBox_color.SelectedText == "Yellow")
    {
        this.BackColor = System.Drawing.Color.Yellow;
    }
    else
    {
        this.BackColor = System.Drawing.Color.Blue;
    }
}

When I click the button, the form's BackColor is always set to Blue. What am I doing wrong here?

2

There are 2 answers

0
Sayse On

You can use Color.FromName

this.BackColor = Color.FromName(comboBox_color.SelectedItem.ToString());

If the name parameter is not the valid name of a predefined color, the FromName method creates a Color structure that has an ARGB value of 0 (that is, all ARGB components are 0).

0
BIBD On

The problem is the property of the ComboBox you are comparing to.

The SelectedText property is used to get or set the text that is selected in the editable portion of a ComboBox.

The SelectedItem property is used to get or set the selected item in the ComboBox. If you wanted to get the Text displayed for that selected item you could do that like this:

comboBox_color.SelectedItem.ToString();