Một số thao tác với Data Binding Author :
Xcross87
Data Binding là cách mapping các thành phần của một data source vào một thành phần GUI và tự động
làm việc với dữ liệu. Ví dụ có thể bind một cột (col) vào một TextBox qua thuộc tính Text hoặc có thể
bind cả một table vào DataGrid như DataGridView.
Có 2 cách bìn WinForm control vào dữ liệu :
• Simple
• Complex
Simple Data Binding
Là cách liên kết một-một giữa một thuộc tính của control và một thành phần của data source, và sử dụng
control để hiển thị duy nhất một giá trị một lần.
Thử một ví dụ :
Tạo Winform App project, tại Form1 bạn cho thêm 2 textbox vào.
Sau đó trong sự kiện : Form1_Load bạn chèn thêm đoạn code sau :
[code]
private void Form1_Load(object sender, EventArgs e)
{
string connString = @"Server = .\SQLEXPRESS;
Integrated Security = true;
Database = Northwind";
string sql = @"SELECT * FROM employees ";
SqlConnection conn = new SqlConnection(connString);
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds, "employees");
textBox1.DataBindings.Add("text", ds, "employees.firstname");
textBox2.DataBindings.Add("text", ds, "employees.lastname");
}
[/code]
Sau đó run thì thấy textbox1 là giá trị firstname đầu tiên trong record và textbox là giá trị lastname tương
ứng.
}
// Tạo BindingManager
private BindingManagerBase bMgr;
// Sự kiện Form1_Load
private void Form1_Load(object sender, EventArgs e)
{
// Tạo connection string
string connString = @"Server = .\SQLEXPRESS;
Integrated Security = true;
Database = Northwind";
// Tạo Sql Query
string sql = @"SELECT * FROM employees ";
// Tạo connectioon
SqlConnection conn = new SqlConnection(connString);
// Tạo Adapter
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
// Tạo DataSet
DataSet ds = new DataSet();
// Lấp đầy DataSet
da.Fill(ds, "employees");
// Bind giá trị cột firstname vào textbox1
textBox1.DataBindings.Add("text", ds, "employees.firstname");
// Bind giá trị cột lastname vào textbox2
textBox2.DataBindings.Add("text", ds, "employees.lastname");
// Cài Binding Manager vào DataSet để quản lý
bMgr = this.BindingContext[ds, "employees"];
}
Page 2 of 3
Một số thao tác với Data Binding Author :
Xcross87