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.
How about using a public Event
I would do it like this.
and call it from Form1 like this.
Then, Form1 could get a text from Form2 when Form2 is closed
Thank you.
After a series of struggle for passing the data from one form to another i finally found a stable answer. It works like charm.
All you need to do is declare a variable as
public static datatype 'variableName'
in one form and assign the value to this variable which you want to pass to another form and call this variable in another form using directly the form name (Don't create object of this form as static variables can be accessed directly) and access this variable value.Example of such is,
Form1
Form2
I've worked on various winform projects and as the applications gets more complex (more dialogs and interactions between them) then i've started to use some eventing system to help me out, because management of opening and closing windows manually will be hard to maintain and develope further.
I've used CAB for my applications, it has an eventing system but it might be an overkill in your case :) You could write your own events for simpler applications
Define a property
In the
form2
Getting the data in
form1
andform3
In this code, you pass a text to Form2. Form2 shows that text in textBox1. User types new text into textBox1 and presses the submit button. Form1 grabs that text and shows it in a textbox on Form1.
And this is Form1 code:
you can pass as parameter the textbox of the Form1, like this:
On Form 1 buttom handler:
On the Form 2