oljo
oljo

Reputation: 59

C# Beginner, trying to change a fixed background color of a form with text in a textbox

I am a total beginner with c#, i am learning with Udemy.

I have done just a little start but now i want to test for my own.

i have learned how to use a button to change the background color of a form.

BackColor = Color.Red; etc.

I am now trying to make a textbox where i can write in for example Red, Blue, Green ect and the click a button, then the form will change to that color. I want to have fixed colors i can choose from so i am guessing i need to make fixed colors in the formload "tab"?

private void FrmColorCalculator_Load(object sender, EventArgs e)
 
            
            Color red = Color.Red;
            Color green = Color.Green;

should this be in formload? how to make fixed colors? i get an errormessages saying "cannot convert system.drawing.color to string, but thats not what i want to do, i want the color to change.

If someone would be willing to kick me in the right direction?

Upvotes: 0

Views: 1085

Answers (4)

Aruna Prabhath
Aruna Prabhath

Reputation: 242

simple change the color of the text inside the textbox using following code.

txtYourTextBox.ForeColor = System.Drawing.Color.Red;

Upvotes: 1

Jingmiao Xu-MSFT
Jingmiao Xu-MSFT

Reputation: 2299

Idle_Mind’s answer can help you change the background color to the color you type in textbox.

If you want to choose fixed colors you can use combobox instead of textbox.

Here is the code:

public Form1()
    {
        InitializeComponent();
        comboBox1.Items.Add("Red");
        comboBox1.Items.Add("Blue");
        comboBox1.Items.Add("Green");
        comboBox1.Items.Add("Yellow");
    }

    private void button1_Click(object sender, EventArgs e)
    { 
            this.BackColor = Color.FromName(comboBox1.Text);
    }

enter image description here

Upvotes: 1

Idle_Mind
Idle_Mind

Reputation: 39122

"I am now trying to make a textbox where i can write in for example Red, Blue, Green ect and the click a button, then the form will change to that color."

Use Color.FromName like this:

private void button1_Click_2(object sender, EventArgs e)
{
    try
    {
        this.BackColor = Color.FromName(textBox1.Text);
    }
    catch (Exception ex)
    {
        MessageBox.Show("Invalid color: " + textBox1.Text);
    }            
}

Upvotes: 2

Amjad S.
Amjad S.

Reputation: 1241

if you want to change form color you can do this by editing the property BackColor,

Form form1= new Form();

private void FrmColorCalculator_Load(object sender, EventArgs e){

     form1.BackColor = Color.Red;
}

f you mean a WPF Window you can use the Background property. From within the Window's code:

Background = Brushes.LightPink;

Upvotes: 0

Related Questions