Multiple Forms question
-
I have an application with multiple forms, and can't figure out how to make their variables and functions visible to one another. This is what I'd like to do:
namespace app1 { public class Form1 { public int state; private void btn_LoadForm_Click(...) { Form2 f = new Form2(); f.Show(); } public void SetState(int x) { state = x; } } public class Form2 { private void Form2_Load (...) { Form1.SetState(1); } }
Why doesn't this work? How do I make this work? Thanks, -mutty -
I have an application with multiple forms, and can't figure out how to make their variables and functions visible to one another. This is what I'd like to do:
namespace app1 { public class Form1 { public int state; private void btn_LoadForm_Click(...) { Form2 f = new Form2(); f.Show(); } public void SetState(int x) { state = x; } } public class Form2 { private void Form2_Load (...) { Form1.SetState(1); } }
Why doesn't this work? How do I make this work? Thanks, -muttyThat doesn't work because Form1 is not an object, it's a class. You have to have a reference to the specific object to access non-static members of the class. You can send a reference to the first form in the constructor of the second form:
Form2 f = new Form2(this);
Add a reference in Form2 and store the reference to the first form:private Form mainForm; public Form2(Form mainForm) { this.mainForm = mainForm; }
Then you can reach the first form:private void Form2_Load(...) { this.mainForm.SetState(1); }
--- b { font-weight: normal; } -
That doesn't work because Form1 is not an object, it's a class. You have to have a reference to the specific object to access non-static members of the class. You can send a reference to the first form in the constructor of the second form:
Form2 f = new Form2(this);
Add a reference in Form2 and store the reference to the first form:private Form mainForm; public Form2(Form mainForm) { this.mainForm = mainForm; }
Then you can reach the first form:private void Form2_Load(...) { this.mainForm.SetState(1); }
--- b { font-weight: normal; } -
I understand all this except the line: this.mainForm = mainForm; Do I need to declare a form mainForm in form2?
-
The line takes the reference to Form1 and stores it in the private variable. "this.mainForm" refers to the private variable in the Form2 class. "mainForm" refers to the parameter that you send to the constructor. --- b { font-weight: normal; }