I am creating a winform application, where i have two forms: form1 and form2. On starting my application the form1 gets loaded. I have included the code to open form2 in form_load method of form1. The form2 contains two textboxes where i need to specify path for files which i will open and use in form1. So my question is how do i pass the values that are in textboxes in form2 to form1.
Asked
Active
Viewed 1,676 times
-4
-
Doing a Google search for ["c# get textbox from other form"](https://www.google.com/search?q=c%23+get+textbox+from+other+form) brings me right to [this](https://www.google.com/search?q=c%23+get+textbox+from+other+form). – Jonathon Reinhart Sep 16 '13 at 07:25
-
@JonathonReinhart....i know it has been asked many times, but the answers didn't solve my problem.....actually when i click ok button that is present in my form2, it closes the form2 and brings the form1 back to foreground and because of this the values of the textboxes r lost. – Kratos Sep 16 '13 at 07:26
-
Well then you have a different problem, don't you? – Jonathon Reinhart Sep 16 '13 at 07:26
-
1@Kratos so please share what you did and we can guide you on the correct path or fix your errors. – Shadow The GPT Wizard Sep 16 '13 at 07:27
-
@ShadowWizard.......i tried using properties in form1 whose values are getting set in form2, but for some reason the values are not getting set.......i am using this.close() to close form2 and then returning to form1. – Kratos Sep 16 '13 at 09:16
3 Answers
1
You can create two public properties (of type string) in your 1st form. And then, on changing the value of your textboxes in your 2nd form, just set the properties of the 1st form. As such, you can freely use your properties in your 1st form.

Nadeem_MK
- 7,533
- 7
- 50
- 61
1
If you set up your form opening correctly you should still have access to it
using(var form = new Form2()
{
if(DialogResult.OK == form.ShowDialog(this))
{
//OK was clicked, do something with the form's properties
// or textboxes if public
string s = form.Textbox1Text;
}
}
You should still be able to use your form whilst inside of this block.
Note: When you close your form you should set the dialog result (you should do this anyway)
DialogResult = DialogResult.OK; // there is also DialogResult.Cancel
Example Form2 property
public string Textbox1Text
{
get{ return textbox1.Text; }
private set { textbox1.Text = value;}
}

Sayse
- 42,633
- 14
- 77
- 146
0
Try this,
Define a property in Form2
which will keep the path string. Once user selects the path from Form2
you have to set that path to this property.
Form1
Assume this is how you open Form2
from Form1
Form2 form = new Form2();
form.Show();
//Getting the path value from property declared in Form2
string pathFromForm2 = form.PathProperty;

Jonathon Reinhart
- 132,704
- 33
- 254
- 328

Kurubaran
- 8,696
- 5
- 43
- 65