Ok, I have a main form where I create and show a second form. In the second form, I want to enter some text, click a button, check the text is valid, then pass that text back to the original form (or access the text in the second form), then eithe r hide or dispose of the second form before processing the original form any further.
The scenario is that I'm creating a chat client and I need to ask for the username before I process the client any further. I have the forms created and ready to go but I can't quite figure how best to get the username from the second form into the main client.
Cheers!

1 answers
Further information. Every page I find regarding passing data between forms seems to only show passing data from form 1 to form 2. I need to know how to get data from form 2 into form 1.
answered 2 years ago by:
223
Ok, the solution is to define your controls in the second form as internal protected to ensure the first form can access them. Then you create an instance of the second form and open it as form2.ShowDialog()
Next you process the second form as you normally would but upon completion, you Close() the second form. You then access the second forms controls as you normally would and hey presto! Done!
answered 2 years ago by:
223
one way you can get data back to form 1 without closing form 2 is to define a delegate, and assign that before you show your form 2, then from form2 call that delegate to pass the data back to form1.
public delegate void Foo(string username);
public class Form2 : Form {
public event Foo Foo1;
public Foo Foo2;
// this is the same for both
void OnFoo1(string uname) {
if(Foo1 != null) Foo1(uname);
}
// where ever you need to send the username back
void Validate() {
// if data is valid
OnFoo(textBox1.Text);
}
}
Form2 code:
Form2 f2 = new Form2();
// depending on if you want it as an event...
// not that it reall matters here
f2.Foo1 += new Foo(FooMethod);
f2.Foo2 = new Foo(FooMethod);
f2.ShowDialog(this);
// FooMethodImplementation for the event
// or delegate from Form2
void FooMethod(string username) {
// or whatever you do w/ this info
this.textBox1.Text = username;
}
answered 2 years ago by:
2309
Cheers MH! That is very useful right now. :-)
answered 2 years ago by:
223
This post was imported from csharpfriends, if you have a similiar question please ask it again.
All previous members have been migrated, hope you enjoy the new platform!