Data transmission between forms:
1. Use the tag attribute of the child form
2. Use a third-party static variable
3. Use the tag attribute of the parent form
Limitations:A form must be closed before data can be passed.
If we want to transfer data without closing any form, what should we do?
In my other blog (Data transmission between forms in winform (2)) The problem can be solved by triggering external events.
Example:
When the user clicks the "add" button in the subwindowCode:
Private Void Button#click ( Object Sender, eventargs e ){ This . Dialogresult = Dialogresult. OK; // Create an Info Object User Info = New User (); // Save data to Info Object Info. Username = Textbox3.text; Info. Password = Textbox4.text; // Question: How to pass the information in the Info Object to the Main Window // Solution 1: Save the object info to the tag attribute of the Child window, and obtain the Info Object Information from the Child Window object instantiated in the parent window. // This. Tag = Info; // Solution 2: Save the object info to a static variable // Third-party. User = Info; // Solution 3: Save the object info to the tag attribute of the parent window. Mainfrm = This . Owner As Mainfrm; mainfrm. Tag = Info ;}
Click the "add information" code in the main window:
Private Void Add User toolstripmenuitem_click ( Object Sender, eventargs e) {frmuser userdialog = New Frmuser (); If (Userdialog. showdialog () = Dialogresult. OK) // If (userdialog. showdialog (this) = dialogresult. OK) { // Solution 1: Use the tag attribute of the subwindow to transmit data between forms User user = userdialog. TagAs User; // Solution 2: Use a third-party static attribute for data transmission User user = Third-party. user; // Solution 3: Use the tag attribute of the parent window to transmit data between forms. Pay attention to passing this parameter to userdialog. showdialog () User user = This . Tag As User; MessageBox. Show ( " User name: " + User. username +" \ R \ n password: " + User. Password );}}
Pay special attention to the third solution. When the information to be passed is saved to the tag of the "Main Window", you must pass a parameter through showdialog when displaying the "subwindow: this is used to set the current form as the owner of the child form
OriginalArticle, Reprint please indicate the source: http://www.cnblogs.com/hongfei/archive/2012/12/17/2822137.html