When writing an Winowsform application, it is very simple to implement a method of passing values between two forms. Here is an example of using the name FormInfo form to get user input information and return this information to FormMain during the run of the main form named FormMain
1. FormMain and FormInfo
Click on the "Modify ..." button to display the FormInfo
2. Setting properties for Buttonok and buttoncancal in FormInfo
3. FormMain Code
Public Partial classFormmain:form { PublicFormMain () {InitializeComponent (); } Private voidButtoninfo_click (Objectsender, EventArgs e) { //instantiate the FormInfo and pass in the initial value to be modified varFormInfo =NewFormInfo (Labelinfo.text); //display FormInfo as a dialog box if(Forminfo.showdialog () = =DialogResult.OK) {//If you click on the "OK" button of frominfo, get the modified information and displayLabelinfo.text =forminfo.information; } } }
4. FormInfo Code
Public Partial classForminfo:form { PublicFormInfo () {InitializeComponent (); } /// <summary> ///constructor Function/// </summary> /// <param name= "info" >information to be modified</param> PublicFormInfo (stringinfo): This() { //displaying the initial value of information in a textboxTextboxinfo.text =info; } /// <summary> ///Get the modified information/// </summary> Public stringInformation {Get{returnTextboxinfo.text;} } }
5. Operation effect
===========
Knowledge Point Extension
Knowledge points 1:formmain and FormInfo are objects. The exchange of information between the two forms is the exchange of information between two objects. Many people are lost in Visual Studio visual programming interface, forget all about this point when programming!
Knowledge point 2: In FormMain Buttonok event handler function, many people mistakenly think that FormInfo is closed, its instance forminfo does not exist. In fact, according to the C # rule, this instance persists until it exits from the function and will be destroyed and given to garbage collection!
Methods for passing values between two forms (WinForm) in Visual Studio