C # uses event mode to pass values between WinForm forms

Source: Internet
Author: User
Tags sendmsg

"Excerpt from: http://www.cnblogs.com/codeToUp/p/5371062.html"

Source code of the project address: Https://github.com/yes-or-no/WinFormTransValueDemoByDelOrEvent.git

C#winform between forms, three method examples, comments in detail. How to use: Use vs2013 to open the compile and run;

A total of three methods were introduced in the project:
# # #方法1: Call its methods to control the subform by saving the object's reference;
# # #方法2: Through a delegate, before the subform is displayed, assign a value to the delegate, focus on the main form of data changes, when there are multiple forms need to receive information, only need to continue to assign a value (+ =) for the delegate, to achieve the decoupling of data transfer;
# # #方法3: Before the subform pops up, registers the event, concerns the change of the main form message, when more than one form needs to receive the information, only needs to register the data to receive the event separately for the form, realizes the decoupling of the data transfer;

Method 2 and Method 3 are the Publish subscription pattern (Observer mode)

The interface for the demo form is as follows:

Open a, b form in MainForm, enter text data in MainForm, click Send Message, a, B's text box will display corresponding data;


The main form is the publisher of the message, form A, B, and so on as the recipient of the message;

Some of the code is as follows (all source code refer to the above link):

1, part of the main form of code:

  1 using System;  2 using System.Collections.Generic;  3 using System.ComponentModel;  4 using System.Data;  5 using System.Drawing;  6 using System.Linq;  7 using System.Text;  8 using System.Threading.Tasks; 9 using System.Windows.Forms; Ten namespace Winfrmdemo {1 public partial class Mainform:form (#region) Recommended)--by saving the object's reference to the object called by the public method to implement the value of the form 18//When the form that receives data is incremented, the code that sends the message needs to be modified, and the corresponding number of form references are added with poor extensibility and high coupling//public Obeserv  Erforma Childforma {get; set;}//public OBESERVERFORMB CHILDFORMB {get; set;} #endregion #region Method 2---The delegate method value 24//The delegate delegate that defines the publication message is a type delegate that can be externally obtained to execute the public Ac  Tion<string> sendmsg {get; set;}  #endregion #region Method 3 (recommended)--Event Mode 29//Add event keyword 30//define a message published events event is a special instance of a delegate Events can only be triggered within the class to execute the EventHandler sendmsgevent; Use the default event handling delegate. #endregionLic MainForm () Notoginseng () InitializeComponent (); Object sender, EventArgs e) #region Method 1 (not recommended)//obeserverforma Childforma = New Obeserverforma (); //childforma = Childforma; //childforma.show (); //OBESERVERFORMB CHILDFORMB = new OBESERVERFORMB (); //CHILDFORMB = CHILDFORMB;  //childformb.show (); Wuyi #endregion #region Method 2---The delegate mode value 54///subform before the popup, assign a value to the delegate, pay attention to the main form message changes, when there are more than one form to receive information, Only this modification can be//obeserverforma Childforma = new Obeserverforma (); //sendmsg + = childforma.settext;//entrusted value of//childforma.show (); //OBESERVERFORMB CHILDFORMB = new OBESERVERFORMB (); //sendmsg + = Childformb.settext;  //childformb.show (); #endregion #region Method 3 (recommended)--event partyType 65//subform Before pop-up, register the event, follow the main form message changes, when there are multiple forms need to receive information, only need to modify here Obeserverforma Childforma = new Obeserve Rforma (); Sendmsgevent + = childforma.mainformtxtchaned;//Register an event for the subform, set the text in the event handling code in the subform childforma.show (); OBESERVERFORMB CHILDFORMB = new OBESERVERFORMB (); Sendmsgevent + = childformb.mainformtxtchaned; Childformb.show ();         #endregion 73 74 75 76} 77 78//When you enter text in MainForm, click Send Message, the text box of the subform displays the data for the main form 79             private void Btnsendmsg_click (object sender, EventArgs e) {Bayi #region Method 1 (not recommended) 82 83 Childforma.settext (This.txtMsg.Text);  //childformb.settext (This.txtMsg.Text); #endregion #region Method 2---Delegate mode value//if (sendmsg!=null) 90/ /{//Sendmsg (This.txtMsg.Text);//Perform all registration of the Commission//} 94 #endregion 95 96             #region Method 3 (recommended)--Event Mode 97//Trigger Event 98//eventargs, write a subclass to inherit the class, add the data information that needs to be encapsulated in the subclass, just pass string         Information, see MyEventArgs sendmsgevent (this,new myeventarg () {text=this.txtmsg.text}); #endregion101 }102}103}

2. Sub-form part a code

 1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks;         9 using system.windows.forms;10 one namespace WinFrmDemo12 {public partial class Obeserverforma:form14 {15 &LT;SUMMARY&GT;16///provide external access to your own elements.//</summary>18//<param name= "TXT" >         </param>19 public void SetText (string txt)-{this.txtMsg.Text = txt;22}23 Public Obeserverforma () InitializeComponent ();}27-public void after Parentfrmtextchange (object sender, EventArgs e) 29 {30//Gets the text from the parent form to myeventarg arg = e a S myeventarg;32 this. SetText (Arg. Text);}34 internal void mainformtxtchaned (object sender, EventArgs e) 36 {37//Fetch to         Text coming from the main form 38    Myeventarg arg = e as myeventarg;39 this. SetText (Arg. Text); 40 41}42}43}

3. Part of sub-form B code

1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using system.windows.forms;10 one namespace WinFrmDemo12 {public     partial class Obeserverformb:form14     {15 16< C2/>public OBESERVERFORMB ()             : {InitializeComponent ();}20///         <summary>22         // Provides external access to your own elements.//</summary>24//         <param name= "txt" ></param>25 public         Void SetText (String txt)-             this.txtMsg.Text = txt;28         }29         internal void mainformtxtchaned ( Object sender, EventArgs e)         {+             //Fetch the text from the main form             myeventarg arg = e as myeventarg;34 this             . SetText (Arg. Text);         }36     }37}

public class Myeventarg:eventargs
{
Pass data information for the main form
public string Text {get; set;}
}

C # uses event mode to pass values between WinForm forms

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.