TheEnd
TheEnd

Reputation: 285

How can I assign ColorDialog.Color to another form in C#?

I am trying to assign the color value returned from ColorDialog on one form to another form.

Form 1 consists of 2 buttons: 'Place Order' (creates a new form with bunch of controls) and 'Select Color' (allows you to change the color of Place Order form). So you can't have Place Order and Select Color open at the same time.

Therefore, I somehow must reference the BackColor property of the Place Order form to form that has the two buttons so that ColorDialog.Color can be assigned to the Place Order form.

Form1 Code:

private void SelectColor_Click(object sender, EventArgs e)
{
    if (colorDialog1.ShowDialog() == DialogResult.OK)
    {
        string color = Convert.ToString(colorDialog1.Color);
        MessageBox.Show(color);
        this.BackColor = colorDialog1.Color; // BackColor is only accessible for this form
    }
}

Upvotes: 0

Views: 2305

Answers (2)

Shekhar_Pro
Shekhar_Pro

Reputation: 18420

The way you are doing this, you will need to maintain a variable to hold the color. Do it like this:

//Declare this private variable to hold the color selected by the user
private System.Drawing.Color selectedcolor;    

private void SelectColor_Click(object sender, EventArgs e)
{
    if (colorDialog1.ShowDialog() == DialogResult.OK)
    {
        selectedcolor = colorDialog1.Color; // BackColor stored in variable
    }
}

then in the code where you launch your new form (Place order button) put this:

private void PlaceOrder_Click(object sender, EventArgs e)
{
    //I am assuming PlaceOrderForm is the name of the class of your other form
    PlaceOrderForm frm = new PlaceOrderForm();
    //Initialize other properties and events,etc.
    //Then make its background color as selected by user
    if(selectedcolor != null) frm.BackColor = selectedcolor;
}

Upvotes: 1

Dustin Davis
Dustin Davis

Reputation: 14585

if(colorDialog1.ShowDialog() != DialogResult.OK) {return;}

form2 f = new form2();
f.BackColor = colorDialog1.Color;
f.Show();

Upvotes: 0

Related Questions