IN VB I was able to go while in Form2:
Form1.Textbox1.Text = ';test';
In a C# it seems that you have to make a new object of that form and then change it:
Form1 theForm = new Form1();
theForm.Textbox1.Text = ';test';;
But this means that the textbox text is only in the new form that you made (theForm). Is there away in which I would either be able to change a form from a different form, or pass information through 2 different forms?
Thank you!C# control open Form from different Form?
There are a number of different ways to solve this. The best solution really depends on the relationship between Form1 and 2.
A common and simple case is that Form1 invoked Form2, and it doesn't really need Text until Form2 is closed.
That's fairly simple: Create a public string property in Form2 and set it's value to ';test'; (or whatever). Form1 can then just access this property after Form2 returns.
If you want to update Form1 as soon as the text is changed, you can use an event for that.
In form 2:
public delegate void TextChanged(string newText);
public event TextChanged Form2TextChanged;
Fire the event when the text changes in Form2:
if (Form2TextChanged != null)
Form2TextChanged(';test';);
In Form1:
form2.Form12TextChanged += new TextChanged(Form2_Form2TextChanged);
If you hit tab at the right time while you key that in, intellisense will fill in the blanks and generate the function for you.
That still has Form1 tightly coupled to form2. Not the best OO design, but adequate for simple cases. (I also cheated to keep things simple by not following the usual pattern for events of passing 2 parameters: object sender, Form2EventArgs args).
To achieve true loose coupling of Form1 and Form2, you want some sort of Publish/Subscribe mechanism. It's overkill for many cases, but it's the 'right' way. Google it if you want more info.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment