How can I pass values from one form to another?
Consider the situation where I have two windows forms, say F1
and F2
. After using F1
, I have now called F2.ShowDialog()
. This puts F2
on the screen as well. Now that both forms are visible, how can I pass data from F1
to F2
? Additionally, once F2
(A modal dialog) finishes, how can I return data to F1
?
Has anyone considered simply passing the value to the form in the tag attribute.
Form newForm = new form();
newForm.Tag = passValue;
newform.showmodal();
when newform is shown the load (or any other) routine can use the data in tag
public void load()
{
if (this.Tag.length > 0)
{
// do something with the data
}
}
Add this code in the relevant place in your from f1.
Form f2 = new Form();
f2.ShowDialog();
HTH
int x=10;
Form1 f2 = new Form1(x);
f2.ShowDialog();
This is wrote in the form who will pass the value. To recive this value you must make new constructor in the recieved form
and that will be like that
public Form2(int x)
{
InitializeComponent();
this.x = x;
}
and will be notice in the first form when you create the instance from form2 you have two choice on of them one of them let you to pass value
Let's say you have a TextBox control in Form1, and you wish to pass the value from it to Form2 and show Form2 modally.
In Form1:
private void ShowForm2()
{
string value = TheTextBox.Text;
Form2 newForm = new Form2();
newForm.TheValue = value;
newForm.ShowDialog();
}
In Form2:
private string _theValue;
public string TheValue
{
get
{
return _theValue;
}
set
{
_theValue = value;
// do something with _theValue so that it
// appears in the UI
}
}
This is a very simple approach, and might not be the best for a larger application (in which case you would want to study the MVC pattern or similar). The key point is that you do things in the following order:
- Create an instance of the form to show
- Transfer data to that new form instance
- Show the form
When you show a form modally it will block the code in the calling form until the new form is closed, so you can't have code there that will transfer information to the new form in a simple way (it's possible, but unnecessarily complicated).
[edit: extended the property methods in Form2 to be more clear]