Purpose: To pass a set of custom parameters to Form1 when you click the button in the subwindow Form2 and display them on the parent window Form1. Method: there are many methods. Here we only introduce how to implement delegation and events. Idea: Define an event in Form2. Form1 creates a Form2 event and subscribes to the event. After a Form2 event is triggered, the parameters are passed to the Form1 and Form1 processing parameters. The Form1 code is as follows:
Using System; using System. collections. generic; using System. componentModel; using System. data; using System. drawing; using System. linq; using System. text; using System. windows. forms; namespace FormDataInteractive {// <summary> // powered by shadu {at} foxmail.com // </summary> public partial class Form1: Form {public Form1 () {InitializeComponent ();} private void button#click (object sender, EventArgs e) {// create Form2 and add the event processing function Form2 frm = new Form2 (); frm. dataChange + = new Form2.DataChangeHandler (DataChanged); frm. showDialog ();} public void DataChanged (object sender, DataChangeEventArgs args) {// update the Form Control textBox1.Text = args. name; textBox2.Text = args. pass ;}}}
The Form2 code is as follows:
Using System; using System. collections. generic; using System. componentModel; using System. data; using System. drawing; using System. linq; using System. text; using System. windows. forms; namespace FormDataInteractive {public partial class Form2: Form {// define the delegate // public delegate void DataChangeHandler (string x); a string public delegate void DataChangeHandler (object sender, dataChangeEventArgs args );/ /Declare the event public event DataChangeHandler DataChange; // call the event function public void OnDataChange (object sender, DataChangeEventArgs args) {if (DataChange! = Null) {DataChange (this, args) ;}} public Form2 () {InitializeComponent () ;}private void button#click (object sender, EventArgs e) {// trigger event, pass the custom parameter OnDataChange (this, new DataChangeEventArgs (textBox1.Text, textBox2.Text) ;}/// <summary> // custom event parameter type, you can set multiple parameters as needed to facilitate the transmission of // </summary> public class DataChangeEventArgs: EventArgs {public string name {get; set;} public string pass {get; set ;} public DataChangeEventArgs (string s1, string s2) {name = s1; pass = s2 ;}}}
Lab results: