namespace WindowsApplication3
{
public partial class Form1 : Form
{
//Define delegate< /p>
public delegate void ChangeTextHandler(string text);//******************** 1
public Form1()< /p>
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)//***** ************* 2
{
Form2 frm2 = new Form2();
frm2.cth = new ChangeTextHandler (ChangeLable);
frm2.Show();
}
///
/// Delegate association method
///
///
public void ChangeLable(string str) //************************************ 3
{< /p>
label1.Text = str;
}
}
}
Another form
namespace WindowsApplication3
{
public partial class Form2 : Form
{
public WindowsApplication3.Form1.ChangeTextHandler cth; //**************** 4
public Form2()
{
InitializeComponent();
p>}
private void button1_Click(object sender, EventArgs e) //**************** 5
{ < /p>
cth(textBox1.Text);
}
}
}
A> First look at 1, Here we define a delegate in the Form1 class. The name of the delegate is ChangeTextHandler, the return value is void, and the parameter is a string;
B>Look at 2, here we are about to create a delegate object, the creation method is the new delegate name (the method referred to by the delegate); the method referred to by the delegate here is ChangeLabel. This method belongs to the Form1 class. Please remember
C>Wait, have you noticed, Who is our entrustee in 2? cth, it is declared in Form2, please see 4, so it belongs to the object created by the Fom2 class, so the writing method of frm2.cth is used
C>Okay, then let’s look at the entire program How it works:
1. vs starts Form1 and Form1 is initialized;
2. The user clicks button1, causing the execution of the button1_Click method;
Form2 frm2 = new Form2(); //The form object frm2 is generated and initialized. At this time, frm2 has a cth delegate statement and a button1_Click method
frm2.cth = new ChangeTextHandler(ChangeLable ); //frm2's cth has officially changed from a statement to a real delegate object, which refers to the ChangeLable method
frm2.Show(); //frm2 display
3. User After clicking button1 on frm2 (you can understand it this way, the form you design in the design view is a class, but when you F5, the form you see is called a form object), the button1_Click method is executed
cth(textBox1.Text); //cth refers to ChangeLabel, which is equivalent to executing ChangeLabel(textBox1.Text). Therefore, the content of the text box on Form 2 is assigned to the label of Form 1!
Please pay attention, brother, your label is spelled incorrectly