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

2.2k views Asked by At

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
    }
}
2

There are 2 answers

2
Shekhar_Pro On

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;
}
0
Dustin Davis On
if(colorDialog1.ShowDialog() != DialogResult.OK) {return;}

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