Reputation: 31251
I have 3 winforms in my project and on Form3 there is a checkbox. What I want to be able to do is to click this checkbox, then when the form is exited make the same check (whether checked or not) on the one in Form1. The existing code I have is follows, but it just won't work, am I missing a trick somewhere? Thanks.
//Form3
Form1 setDateBox = new Form1();
setDateBox.setNoDate(checkBox1.Checked);
//Form1
public void setNoDate(bool isChecked)
{
checkBox1.Checked = isChecked;
}
Upvotes: 2
Views: 1568
Reputation: 12894
A couple of approaches:
1 - Store the Form1 variable "setDateBox" as a class member of Form3 and then access the "setNoDate" method from the checkboxes CheckedChanged event handler:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
setDateBox.setNoDate(checkBox1.Checked);
}
2 - If you do not wish to store setDateBox as a class member or you need to update more than one form, you could Define an event within Form3 which like so:
public event EventHandler<CheckedChangedEventArgs> CheckBox1CheckedChanged;
...
public class CheckedChangedEventArgs : EventArgs
{
public bool CheckedState { get; set; }
public CheckedChangedEventArgs(bool state)
{
CheckedState = state;
}
}
Create a handler for the event in Form1:
public void Form1_CheckBox1CheckedChanged(object sender, CheckedChangedEventArgs e)
{
//Do something with the CheckedState
MessageBox.Show(e.CheckedState.ToString());
}
Assign the event handler after creating the form:
Form1 setDateBox = new Form1();
CheckBox1CheckedChanged += new EventHandler<CheckedChangedEventArgs>(setDateBox.Form1_CheckBox1CheckedChanged);
And then fire the event from Form3 (upon the checkbox's checked state changing):
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if(CheckBox1CheckedChanged != null)
CheckBox1CheckedChanged(this, new CheckedChangedEventArgs(checkBox1.Checked));
}
Hope this helps.
Upvotes: 3
Reputation: 3322
You are creating a new instance of Form1 and not referencing the existing instance of it.
Form1 setDateBox = (Form1)this.Owner
That should fix your problem.
Upvotes: 2
Reputation:
In the designer of the form containing checkbox, Make it to internal or public. Then you can access the control from the forms object. Its a quick and dirty way to achieve but it might solve your issue.
ex
In form1.designer.cs
existing
private CheckBox checkbox1;
new one
internal CheckBox checkbox1; or
public CheckBox checkbox1;
Upvotes: 2
Reputation: 26446
checkBox1
is a member of Form3
, so from Form1
you cannot reference it that way.
You could:
Form3.checkBox1
publically visible, so you can reference it by myForm3Instance.checkBox1
Upvotes: 2