Reputation: 13
I have a project with 2 forms, the first form is empty. The second form has 5 buttons.
When I press a button, it opens a color dialog. I'm choosing a color, and button's background color is changing. For example, if button1
's background color id is Green
, form1
's background color should be green. Not instant but when I press the Save button. I need to get button's background color into a variable. How can I do this?
private void btnKAMU_Click(object sender, EventArgs e)
{
colorDialog1.ShowDialog();
btnKAMU.BackColor = colorDialog1.Color;
}
Upvotes: 0
Views: 801
Reputation: 32248
You can pass a reference of Form1
to Form2
setting Form2
Owner
, with a custom Property or using Form2
constructor.
When, in Form1
, you create an instance of Form2
:
Using then Owner property:
(Form2
Owner
is set when you instantiate a Form this way:
form2.Show(this);
. The this
reference is Form2
Owner - Form1
here).
Form2 form2 = new Form2();
form2.Show(this);
//form2.ShowDialog(this);
In Form2
, set the Owner
BackColor
property:
private void btnSAVE_Click(object sender, EventArgs e)
{
this.Owner.BackColor = btnKAMU.BackColor;
}
Form2 form2 = new Form2();
form2.Form1Reference = this;
form2.Show();
//form2.ShowDialog();
In Form2
, using a property value:
public Form Form1Reference { get; set; }
private void btnSAVE_Click(object sender, EventArgs e)
{
this.Form1Reference.BackColor = btnKAMU.BackColor;
}
Form1
in Form2
constructor:Form2 form2 = new Form2(this);
form2.Show();
//form2.ShowDialog();
With a property value as before:
private Form Form1Reference { get; set; }
public Form2(Form Form1Instance)
{
this.Form1Reference = Form1Instance;
InitializeComponent();
}
private void btnSAVE_Click(object sender, EventArgs e)
{
this.Form1Reference.BackColor = btnKAMU.BackColor;
}
Or assign the Form1
reference to a private Field:
private Form Form1Reference;
public Form2(Form Form1Instance)
{
this.Form1Reference = Form1Instance;
InitializeComponent();
}
private void btnSAVE_Click(object sender, EventArgs e)
{
this.Form1Reference.BackColor = btnKAMU.BackColor;
}
Depending on your context, it could be necessary to assing the chosen Color to a private Field and use its value to change Form1.BackColor
private Color Form1BackColor;
private void btnKAMU_Click(object sender, EventArgs e)
{
colorDialog1.ShowDialog();
btnKAMU.BackColor = colorDialog1.Color;
this.Form1BackColor = btnKAMU.BackColor;
}
Change the previous code using this value if needed.
Upvotes: 2