There are so many methods (How many? I don’t know) to pass data between forms in windows application. In this article let me take four important (easiest) ways of accomplishing this.
- Using constructor
- Using objects
- Using properties
- Using delegates
The Constructor Approach
This could be the easiest method of all. A method is invoked whenever you instantiate an object. This method is called a constructor. Code a constructor for form2 class with one string parameter. In the constructor assign the text to the label’s text property. Instantiate form2 class in form1’s button click event handler using the constructor with one string parameter and pass the textbox’s text to the constructor.
The Object Approach
Objects are reference types, and are created on the heap, using the keyword new. Here we are going to pass data using objects. The approach is simple; in form2 we are going to instantiate form1 class. Then instantiate form2 in the button click event handler of form1. After this we are going to pass form1 object to the form2 using form2’s form1 object. The last step is to invoke the form2 window by calling the form2’s show method.
The Properties Approach
The Delegates Approach
Winding up...
These four approaches are very simple in implementing data passing between forms. There are also other methods available in accomplishing the same. Source code for the methods I stated above is given at the top for download. It is time for you to put your thinking cap and find other ways of doing this. Happy Coding!!!
For source code and further reading...
2 comments:
good article...few lines of code as examples would make things clearer
Here you can download the code samples:
http://www.c-sharpcorner.com/UploadFile/thiagu304/passdata05172006234318PM/passdata.aspx
http://www.codeproject.com/KB/cs/PassDataWinForms.aspx
Post a Comment