-Cách làm này:
-Ta sẽ tạo 2 form A ,B
+A có 1 label để hiện thị chuỗi nhập vào từ form B,và 1 cái button để tạo form B.
+B có 1 textbox để nhập chuỗi cần truyền cho A,và 1 button để truyền.
-Đối với form B code:
public partial class B : Form
{
public B()
{
InitializeComponent();
this.button1.Click += new EventHandler(button1_Click);
}
public delegate void SEND(string s); //delegate tham chiếu tới 1 hàm kiểu void tênham(string s);
public SEND sender; //1 biến kiểu SEND
void button1_Click(object sender, EventArgs e)
{
this.sender(textBox1.Text); //thực thị công việc của hàm mà sender tham chiếu tới.
}
private void B_Load(object sender, EventArgs e)
{
}
}
-Đối với form A (form main):
public partial class A : Form
{
public A()
{
InitializeComponent();
this.button1.Click += new EventHandler(button1_Click);
}
void button1_Click(object sender, EventArgs e)
{
B tauit = new B(); //tạo 1 form B
tauit.sender = new B.SEND(getString); //cho sender của form mới tạo tham chiếu tới hàm getString của form A.
tauit.ShowDialog();
}
public void getString(string s //1 hàm giống với kiểu hàm mà delegate bên form B có thể tham chiếu tới.
{
this.label1.Text=s; //Gán chuỗi s cho label của form A
}
}
Như vậy sau khi tạo form B và nhập chuỗi vào textbox của form B ,rồi click button ở form B thì.void button1_Click(object sender, EventArgs e)
{
this.sender(textBox1.Text); //thực thị công việc của hàm mà sender tham chiếu tới.
}
-->lúc này sender đang tham chiếu tới hàm getString của form A nên this.sender(textBox1.Text); cũng chính là gọi getString(textBox1.Text); mà hàm getString làm gì thì bạn rõ rồi chứ?
Không có nhận xét nào :
Đăng nhận xét