user459057
user459057

Reputation: 53

How to share data between forms?

Consider two forms: form1 and form2

form1 calls form2:

form2 frm = new form2()
frm.show

form2 shows a grid with data. When data is selected, it's put into a textbox.

I need the return value from form2 to form1 when it's closed.

How can this be done?

Upvotes: 3

Views: 5310

Answers (2)

Ghorban ali arabi
Ghorban ali arabi

Reputation: 1

if you change Modifiers Property of a control in a Form to Public, another Forms can access to that control. f.e. :

Form2 frm; 
private void Form1_Load(object sender, EventArgs e) 
{ 
    frm = new Form2(); 
    frm.Show(); 
} 
private void button1_Click(object sender, EventArgs e) 
{ 
    MessageBox.Show(frm.txtUserName.Text); 
    //txtUserName is a TextBox with Modifiers=Public
}

Upvotes: 0

SLaks
SLaks

Reputation: 888213

Add a public property to your Form2 class that returns the selected item.

Then, replace the Show() call with ShowDialog() (a blocking method) and check the property afterwards.

Also, rename your forms.

Upvotes: 5

Related Questions