Click to See Complete Forum and Search --> : passing data from Form2 to Form1


sangfroid
September 11th, 2008, 09:14 AM
Hi,
I have 2 forms , Form1 and Form2. When I click on the "Ok" buttom of the Form 1, it creates an instance of Form2 as below

Form2 newform = new Form2();
newform.Show();


Form2 has a textbox which accepts input from user. I am able to get the Form2 and its textbox, but I am having problems of passing data from Form2 to Form1. Sending data from Form1 to Form2 is not a problem. But here it is the reverse case. How do i pass the data in textbox of Form2 to Form1 ??

eclipsed4utoo
September 11th, 2008, 09:23 AM
set the "Modifiers" property of the textbox to "Public", then...


newform.ShowDialog();
string dataFromForm = newform.textBox1.Text;
newform.Dispose();

MMH
September 11th, 2008, 09:33 AM
Hi,
I have 2 forms , Form1 and Form2. When I click on the "Ok" buttom of the Form 1, it creates an instance of Form2 as below

Form2 newform = new Form2();
newform.Show();


Form2 has a textbox which accepts input from user. I am able to get the Form2 and its textbox, but I am having problems of passing data from Form2 to Form1. Sending data from Form1 to Form2 is not a problem. But here it is the reverse case. How do i pass the data in textbox of Form2 to Form1 ??

Use delegate and events to send info from form2 to form1
Have a look into the attached file....

Hope this is what you are looking for..
MMH...

darwen
September 11th, 2008, 03:29 PM
It depends on how you want Form2 to behave.

If you want it to behave like a FileOpen dialog (i.e. stops all input into Form1 until it's closed) use eclipsed4utoo's suggestion but with one change :

DONT MAKE MEMBER VARIABLES PUBLIC

This breaks encapsulation. You should instead have a public property which returns the text in the text box e.g.


public class Form2 : Form
{
private TextBox _textBox;

public string TextBoxText
{
get
{
return _textBox.Text;
}
}
}


However if you want Form2 to open and stay open whilst the user does things with Form1 then you should use MMH's suggestion of having an event.

Darwen.

Talikag
September 12th, 2008, 06:48 AM
You can also send data through the constructor of Form2...

Form2 form2 = new Form2("hi", "sup?", "bye");
using(form2)
{
form2.ShowDialog();
}

MMH
September 12th, 2008, 07:26 AM
You can also send data through the constructor of Form2...

Form2 form2 = new Form2("hi", "sup?", "bye");
using(form2)
{
form2.ShowDialog();
}


He wants to send data from form2 to form1 and not vice-versa.