1. Function display
Sometimes it is necessary to pass the content of the child interface to the parent interface, and there are several methods. Often used is achieved through delegation. The specific effects are as follows:
[Description] Click the "Open sub-interface" button on the parent interface, and the sub-interface will pop up. The parent interface and child interface are shown in the figure above.
[Description] Enter the content to be returned to the parent interface in the textBox box of the sub interface, click the "Return content" button, and the textBox of the parent interface will display the returned content. Specifically as shown in the figure above
2. Code Analysis
Inside the application delegate (delegate) and event (event). Delegation is the most commonly used "callback method" (callback) in front-end development, and event is a registration mechanism that associates actions with delegation.
In order to achieve the above functions, first write the definition of the subform. code show as below:
public partial class Form2 : Form
{
//第二步:声明一个委托类型的事件
public event setTextValue setFormTextValue;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//第三步:准备相关数据。
setFormTextValue(this.textBox1.Text);
}
}
// 第一步:声明一个委托。(根据自己的需求)
public delegate void setTextValue(string textValue);
Step 1: First define a delegate in the subform. Define delegation according to actual needs
Step 2: Declare an event in the subform and associate the delegate with the action
Step 3: Implement event in specific events
Refer to the code of Form2 for the above three steps
The code of the parent form is as follows:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
//第四步:初始化事件
form2.setFormTextValue += new setTextValue(form2_setFormTextValue);
form2.Show();
}
//第五步:实现事件
void form2_setFormTextValue(string textValue)
{
//具体实现。
this.textBox1.Text = textValue;
}
}
In the specific implementation of the parent form, it is divided into 2 steps:
Step 4: When defining the subform, declare the event of the subform
Step 5: Implement specific events
above, that's all
3. Function analysis
By way of entrustment, advantages: loose coupling.
4. Source code download
[Description] Because CSDN will automatically increase the threshold for downloading old codes to 50 gold coins, so I share the codes to Baidu Cloud. The specific link is as follows
Download link extraction code: zkeu