Ramon Fonis
Ramon Fonis

Reputation: 167

Changing Background color of Form using string via Textbox

I am using the following code so as to get the color of Form's background from user using a TextBox, if the color matches the C# colors, then change the Form background color to what user entered, otherwise it shows a message that the color doesn't exist.

The problem is there is no way to read colors from string consisting the name of colors. So I can't use

Form1.ActiveForm.BackColor = Color.text

What can I do to resolve that?

private void button1_Click(object sender, EventArgs e)
{
  string text = textBox1.Text;
  string[] colors = Enum.GetNames(typeof(System.Drawing.KnownColor));
  for (int i = 0; i < colors.Length; i++)
  {
    if (colors[i] == text)
    {
      // Form1.ActiveForm.BackColor = Color.
      MessageBox.Show("BackGround Color of Form Has Been Changed");
    }
    else
    {
      MessageBox.Show("Color You Entered Does Not Exist");
    }
  }
}

Upvotes: 2

Views: 1687

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

You can use such code:

this.BackColor = (Color)new ColorConverter().ConvertFromString(textbox1.Text);

But better than a TextBox is a ComboBox containing colors. You can fill the ComboBox using KnowsColor or any other list of color names:

comboBox1.DataSource = Enum.GetValues(typeof(KnownColor)).Cast<KnownColor>().ToList();

Then when you want to get selected color from ComboBox:

if(comboBox1.SelectedIndex>=0)
    this.BackColor = Color.FromKnownColor((KnownColor)comboBox1.SelectedValue);

Upvotes: 3

Related Questions