[C#] Hướng dẫn sử dụng delegate để truyền dữ liệu giữa 2 form
Bài viết hôm nay, mình xin hướng dẫn các bạn sử dụng Delegate trong C# để truyền dữ liệu qua lại giữa hai form với nhau. Ngoài ra các bạn có thể dùng từ khòa Static để truyền dữ liệu giữa các class.
C# HƯỚNG DẪN TRUYỀN DỮ LIỆU GIỮA 2 FORM
Nhưng trong bài viết này, mình sử dụng Delegate C#
Giao diện demo ứng dụng:
Source code Form 1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DelegateDemo
{
public delegate void SendMessage(String value);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Ta tạo một delegate để tham chiếu
// Tiếp theo ta tạo một phương thức dùng để set giá trị cho textbox form chính
// Ta tạo thêm một form mới
Form2 f2 = new Form2(SetValue);
// Ta truyền hàm SetValue qua form 2, và form 2 khi nhấn nút button bên đó sẽ gọi lại phương thức SetValue bên này
f2.ShowDialog();
}
private void SetValue(String value)
{
this.textBox1.Text = value;
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Source code cho form 2:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DelegateDemo
{
public partial class Form2 : Form
{
// Bên form 2 ta tạo thêm một delegate dùng để truyền hàm delegate bên form chính qua
public SendMessage send;
public Form2()
{
InitializeComponent();
}
// Tạo một phương thức khởi tạo mới
public Form2(SendMessage sender)
{
// Phương thức khởi tạo này ta sẽ gọi ở bên form 1
InitializeComponent();
this.send = sender;
}
private void button1_Click(object sender, EventArgs e)
{
// Tại sự kiện nhấn nút button bên form 2, ta sẽ gọi lại hàm delegate
this.send(this.textBox1.Text);
// ta gọi như trên để gọi làm hàm bên form 1, và truyền giá trí this.txtBox1.Text qua form 1
}
private void Form2_Load(object sender, EventArgs e)
{
}
}
}
Các bạn có thể thiết kế 2 form như giao diện bên trên vào copy 2 đoạn code này vào 2 form rồi chạy ứng dụng.
Chúc các bạn thành công!