I want to pass values between two Forms (c#). How can I do it?
I have two forms: Form1 and Form2.
Form1 contains one button. When I click on that button, Form2 should open and Form1 should be in inactive mode (i.e not selectable).
Form2 contains one text box and one submit button. When I type any message in Form2's text box and click the submit button, the Form2 should close and Form1 should highlight with the submitted value.
How can i do it? Can somebody help me to do this with a simple example.
There are several solutions to this but this is the pattern I tend to use.
And...
declare string in form1 public string TextBoxString;
in form1 click event add
in form2 constructer
in form2 crate variable Form1 firstformRef;
Ok so
Form1
has a textbox, first of all you have to set thisForm1
textbox to public in textbox property.Code Form1:
Pass
Form1
asthis
in the constructor.Code Form2:
You can make use of a different approach if you like.
Using System.Action
You can think of it as a callback function passed to the child form.
OpenForms Method
This method is easy (2 lines). But only works with forms that are open. All you need to do is add these two lines where ever you want to pass some data.
I provided my answer to a similar question here
Declare a public string in
form1
In button of
form1
To send data to
form1
you can try any event and code following in that eventNow after closing of
form2
and opening ofform1
, you can use returned data ingetdata
string.if you change Modifiers Property of a control in a Form to Public, another Forms can access to that control. f.e. :