Tải bản đầy đủ (.pdf) (8 trang)

Tài liệu Hướng dẫn thực hành Winforms với C# pptx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (171.07 KB, 8 trang )

Hướng dẫn thực hành Winforms với C# Chương 5: ADO.NET
Hue-Aptech | Trần Văn Long – Email: Trang 1



CHƯƠNG 5 – ADO.NET
Từ ứng dụng, ta có thể kết nối và thao tác với cơ sở dữ liệu bằng 2 phương pháp sau:
1. Kết nối thường xuyên
2. Kết nối không thường xuyên
Phần 1. Kết nối thường xuyên
1. Các bước thực hiện
Bước 1: Sử dụng Connection để kết nối đến cơ sở dữ liệu
Bước 2: Thiết lập câu lệnh thực thi: Insert, Select, Update, Delete
Bước 3: Thực hiện lệnh
• Mở kết nối
• Thực thi câu lệnh, xử lý dữ liệu trả về
• Đóng kết nối
2. Ví dụ mẫu
Thiết kế giao diện gồm các phần như hình sau:

- Khi Load form các dữ liệu từ bảng
Customers
trong CSDL
Northwind
của SQL Server
2000 sẽ được hiển thị trên ListView và DataGridView
- Khi chọn 1 dòng trên ListView hoặc DataGridView, dữ liệu của dòng tương ứng sẽ hiển thị
trên các TextBox
- Khi click vào nút Insert, dữ liệu trong các Textbox được thêm vào cơ sở dữ liệu
- Khi click vào nút Update, record được chọn sẽ được chỉnh sửa và cập nhật vào CSDL
- Khi click nút Delete, record được chọn sẽ bị xóa khỏi CSDL


Hướng dẫn thực hành Winforms với C# Chương 5: ADO.NET
Hue-Aptech | Trần Văn Long – Email: Trang 2


Ví dụ 1: đọc dữ liệu từ bảng
Customers
trong CSDL
Northwind
của SQL Server 2000 và
hiển thị lên ListView và DataGridView
// 1. Thiết lập kết nối
string strConn = "server=.; Database = Northwind; uid=sa; pwd=;";
SqlConnection cnNorth = new SqlConnection(strConn);
// 2. Thiết lập câu lệnh
string sqlSelect = "select CustomerID, CompanyName, Address, City from
Customers";
SqlCommand cmdNorth = new SqlCommand(sqlSelect, cnNorth);
cmdNorth.Connection.Open();
// 3. Thực hiện lệnh
SqlDataReader reader = cmdNorth.ExecuteReader();
// Lấy dữ liệu để hiển thị, xử lý qua đối tượng Reader
// Xem ví dụ 1.1 hoặc ví dụ 1.2
// …
// Đóng kết nối
cmdNorth.Connection.Close();
Ví dụ 1.1: Đoạn chương trình sau mô tả việc đọc dữ liệu từ đối tượng reader và hiển thị lên
ListView
CustomerInfo cm; // Xem ví dụ 1.3
while (reader.Read())
{

cm = new CustomerInfo();
cm.CustId = reader.GetString(0);
cm.ContactName = reader.GetString(1);
if (reader.IsDBNull(2))
cm.CustAddress = "";
else
cm.CustAddress =reader.GetString(2);

if (reader.IsDBNull(3))
cm.City = "";
else
cm.City =reader.GetString(3);
ListViewItem lvItem = new ListViewItem(cm.CustId);
lvItem.SubItems.Add(cm.ContactName);
lvItem.SubItems.Add(cm.CustAddress);
lvItem.SubItems.Add(cm.City);
lvItem.Tag = cm;
lsvCustomer.Items.Add(lvItem);
}

Ví dụ 1.2: Đoạn chương trình sau mô tả việc đọc dữ liệu từ đối tượng reader và hiển thị lên
DataGridView
ArrayList list = new ArrayList();

CustomerInfo cm; // Xem ví dụ 1.3
while (reader.Read())
{
cm = new CustomerInfo();
cm.CustId = reader.GetString(0);
cm.ContactName = reader.GetString(1);

if (reader.IsDBNull(2))
cm.CustAddress = "";
else
cm.CustAddress =reader.GetString(2);

if (reader.IsDBNull(3))
cm.City = "";
else
cm.City =reader.GetString(3);

list.Add(cm);

Hướng dẫn thực hành Winforms với C# Chương 5: ADO.NET
Hue-Aptech | Trần Văn Long – Email: Trang 3


}
dataGridView1.DataSource = list;


Ví dụ 1.3:
CustomerInfo
là lớp mô tả các thông tin về đối tượng Customer.
CustomerInfo

được viết như sau:
public class CustomerInfo
{
string custId;
string contactName;

string custAddress;
string city;
public CustomerInfo()
{ }
public CustomerInfo(string custId, string contactName, string custAddress,
string city)
{
this.custId = custId;
this.contactName = contactName;
this.custAddress = custAddress;
this.city = city;
}
public string CustId
{
get {return custId;}
set {custId = value;}
}
public string ContactName
{
get {return contactName;}
set {contactName = value;}
}
public string CustAddress
{
get {return custAddress;}
set {custAddress = value;}
}
public string City
{
get {return city;}

set {city = value;}
}
}

Ví dụ 2: Lấy dữ liệu từ các Textbox: txtID, txtName, txtẢddress và txtCity để lưu vào Database
và cập nhật mới dữ liệu hiển thị trên form
private void cmdInsert_Click(object sender, System.EventArgs e)
{
// 1. Kết nối
string strConn = "server=(local); Database = Northwind; uid=sa; pwd=;";
SqlConnection cnNorth = new SqlConnection(strConn);
// 2. Thiết đặt câu lệnh thực thi
string sqlInsert= "insert into Customers(CustomerID, " +
"CompanyName, Address, City) values(@CustomerID, @CompanyName, "+
"@Address, @City)";
SqlCommand cmdNorth = new SqlCommand(sqlInsert, cnNorth);
cmdNorth.Parameters.Add("@CustomerID", SqlDbType.NChar);
cmdNorth.Parameters.Add("@CompanyName", SqlDbType.NChar);
cmdNorth.Parameters.Add("@Address", SqlDbType.NChar);
cmdNorth.Parameters.Add("@City", SqlDbType.NChar);
cmdNorth.Parameters[0].Value = txtID.Text;
cmdNorth.Parameters[1].Value = txtName.Text;
cmdNorth.Parameters[2].Value = txtAddress.Text;
Hướng dẫn thực hành Winforms với C# Chương 5: ADO.NET
Hue-Aptech | Trần Văn Long – Email: Trang 4


cmdNorth.Parameters[3].Value = txtCity.Text;
// 3. Thực thi lệnh
cmdNorth.Connection.Open();

int kq = cmdNorth.ExecuteNonQuery();
if (kq > 0)
{
MessageBox.Show("Dữ liệu đã cập nhật!");
// Gọi lại hàm Load dữ liệu ở Ví dụ 1
}
else
{
MessageBox.Show("Có lỗi xãy ra!");
}
cmdNorth.Connection.Close();
}

Ví dụ 3: Chọn 1 dòng trên ListView dữ liệu tương ứng sẽ hiển thị trên các TextBox.
private void lsvCustomer_SelectedIndexChanged(object sender,
System.EventArgs e)
{
if (lsvCustomer.SelectedItems.Count == 0)
return;
CustomerInfo cm = lvCustomer.SelectedItems[0].Tag as CustomerInfo;
txtID.Text = cm.CustId;
txtName.Text = cm.ContactName;
txtAddress.Text = cm.CustAddress;
txtCity.Text = cm.City;
}
Ví dụ 4: Lưu dữ liệu sau khi đã hiệu chỉnh trên TextBox vào CSDL
private void cmdUpdate_Click(object sender, System.EventArgs e)
{
if (lsvCustomer.SelectedItems.Count == 0)
return;

// Lấy thông tin về đối tượng đang được chọn
CustomerInfo old = lsvCustomer.SelectedItems[0].Tag as CustomerInfo;
// Lấy thông tin sau khi đã chỉnh sửa
CustomerInfo cm = new CustomerInfo(txtID.Text, txtName.Text,
txtAddress.Text, txtCity.Text);
// 1. Đối tượng kết nối
string strConn = "server=(local); Database = Northwind; uid=sa; pwd=;"
SqlConnection cnNorth = new SqlConnection(strConn);
// 2. Câu lệnh thực thi
string sqlUpdate ="update Customers set CustomerID = "+
"@CustomerID, CompanyName = @CompanyName, Address = @Address, "+
"City = @City where CustomerID = @OrigCustomerID";
SqlCommand cmdNorth = new SqlCommand(sqlUpdate, cnNorth);
cmdNorth.Parameters.Add("@CustomerID", SqlDbType.NChar);
cmdNorth.Parameters.Add("@CompanyName", SqlDbType.NChar);
cmdNorth.Parameters.Add("@Address", SqlDbType.NChar);
cmdNorth.Parameters.Add("@City", SqlDbType.NChar);
cmdNorth.Parameters.Add("@OrigCustomerID", SqlDbType.NChar);
cmdNorth.Parameters[0].Value = cm.CustId;
cmdNorth.Parameters[1].Value = cm.ContactName;
cmdNorth.Parameters[2].Value = cm.CustAddress;
cmdNorth.Parameters[3].Value = cm.City;
cmdNorth.Parameters[4].Value = old.CustId;
// 3. Thực thi lệnh
cmdNorth.Connection.Open();
int kq = cmdNorth.ExecuteNonQuery();
if (kq > 0)
{
MessageBox.Show("Cập nhật thành công!");
//Gọi lại phương thức Load dữ liệu ở Ví dụ 1

}
else
Hướng dẫn thực hành Winforms với C# Chương 5: ADO.NET
Hue-Aptech | Trần Văn Long – Email: Trang 5


MessageBox.Show("Lỗi!");
cmdNorth.Connection.Close();
}

Ví dụ 5: Xóa dòng được chọn
private void cmdDelete_Click(object sender, System.EventArgs e)
{
if (lsvCustomer.SelectedItems.Count == 0)
return;
// Lấy thông tin về đối tượng đang được chọn
CustomerInfo cm = lsvCustomer.SelectedItems[0].Tag as CustomerInfo;
// 1. Đối tượng kết nối
string strConn = "server=(local); Database = Northwind; uid=sa; pwd=;"
SqlConnection cnNorth = new SqlConnection(strConn);
// 2. Câu lệnh thực thi
string sqlUpdate ="Delete from Customers where CustomerID=@CustomerID";
SqlCommand cmdNorth = new SqlCommand(sqlUpdate, cnNorth);
cmdNorth.Parameters.Add("@CustomerID", SqlDbType.NChar);
cmdNorth.Parameters[0].Value = cm.CustId;
// 3. Thực thi lệnh
cmdNorth.Connection.Open();
int kq = cmdNorth.ExecuteNonQuery();
if (kq > 0)
{

MessageBox.Show("Cập nhật thành công!");
//Gọi lại phương thức Load dữ liệu ở Ví dụ 1
}
else
MessageBox.Show("Lỗi!");
cmdNorth.Connection.Close();
}


3. Bài tập

Bài 1: Thiết kế CSDL và Xây dựng ứng dụng quản lý thông tin khách hàng với các yêu cầu
sau:
- Form Đăng nhập: để đăng nhập trước khi sử dụng ứng dụng



- Kiểm tra dữ liệu rỗng trước khi thực
hiện việc xử lý đăng nhập
- Nếu đăng nhập thành công thì cho phép
sử dụng phần Quản lý
- Form Quản lý: có giao diện như hình bên dưới, form này để xem, thêm, sửa, xóa thông tin
của khách hàng. Các thông tin cần quản lý bao gồm: mã số, họ tên, ngày sinh, địa chỉ,
điện thoại, email, hình ảnh
o Thông tin khách hàng sẽ hiển thị ngay khi vào form Quản lý
o Thêm mới: thêm mới 1 khách hàng vào CSDL
o Cập nhật: Chỉnh sửa thông tin 1 khách hàng trong CSDL
o Xóa: Xóa thông tin một khách hàng
Hướng dẫn thực hành Winforms với C# Chương 5: ADO.NET
Hue-Aptech | Trần Văn Long – Email: Trang 6





Phần 2. Kết nối không thường xuyên (Disconnected Architecture)
1. Các bước thực hiện
Bước 1: Sử dụng Connection để kết nối đến cơ sở dữ liệu
Bước 2: Tạo đối tượng DataSet
Bước 3: Tạo đối tượng DataAdapter và các câu lệnh thực thi trên dữ liệu
Bước 4: Đổ dữ liệu vào DataSet
Bước 5: Tương tác, xử lý dữ liệu trên DataSet
Bước 6: Lưu vào CSDL

2. Ví dụ mẫu


Hướng dẫn thực hành Winforms với C# Chương 5: ADO.NET
Hue-Aptech | Trần Văn Long – Email: Trang 7


public partial class Form1 : Form
{
private DataSet ds;
private SqlConnection objConn;
private SqlDataAdapter objDa;
private string STRCONN = "Server=.;Database=BMS;uid=sa;pwd=;";
public Form1()
{
InitializeComponent();


}
private void loadData()
{
objConn = new SqlConnection(STRCONN);
ds = new DataSet();

objDa = new SqlDataAdapter("SELECT * FROM Books", objConn);

//Tạo các câu lệnh Insert, Update, Delete tự động
SqlCommandBuilder cmb = new SqlCommandBuilder(objDa);

objDa.Fill(ds, "Books");

//Do du lieu len DataGridView
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Books";

//Bind du lieu len TextBox
txtID.DataBindings.Add("Text", ds, "Books.BookID");
txtTypeID.DataBindings.Add("Text", ds, "Books.TypeID");
txtTitle.DataBindings.Add("Text", ds, "Books.Title");
txtPublisher.DataBindings.Add("Text", ds, "Books.Publisher");
txtAuthor.DataBindings.Add("Text", ds, "Books.Author");
txtPrice.DataBindings.Add("Text", ds, "Books.Price");
}
private void Form1_Load(object sender, EventArgs e)
{
loadData();
}


private void cmdDelete_Click(object sender, EventArgs e)
{
int i = (int)this.BindingContext[ds, "Books"].Position;
ds.Tables[0].Rows[i].Delete();
objDa.Update(ds, "Books");
}
private void cmdAddNew_Click(object sender, EventArgs e)
{
txtID.Enabled = true;
txtTypeID.Enabled = true;
txtTitle.Enabled = true;
txtAuthor.Enabled = true;
txtPublisher.Enabled = true;
txtPrice.Enabled = true;
this.BindingContext[ds, "Books"].AddNew();
}

private void cmdUpdate_Click(object sender, EventArgs e)
{
//txtID.Enabled = true;
txtTypeID.Enabled = true;
Hướng dẫn thực hành Winforms với C# Chương 5: ADO.NET
Hue-Aptech | Trần Văn Long – Email: Trang 8


txtTitle.Enabled = true;
txtAuthor.Enabled = true;
txtPublisher.Enabled = true;
txtPrice.Enabled = true;
}

private void cmdSave_Click(object sender, EventArgs e)
{
objDa.Update(ds,"Books");
}
}

3. Một số đoạn code mẫu
// Get current Rowposition
CurrencyManager cm = (CurrencyManager)this.BindingContext[ds,"Books"];
long rowPosition = (long)cm.Position;
// Combobox Databinding
cboTypeID.DataSource = ds;
cboTypeID.DisplayMember = "Books.TypeName";
cboTypeID.ValueMember = "Books.TypeID";
// Position to prev Record in Customer
private void btnPrev_Click(object sender, System.EventArgs e)
{
if (this.BindingContext[ds,"Books"].Position > 0)
{
this.BindingContext[ds,"Books"].Position ;
}
}
// Position to next Record in Customer
private void btnNext_Click(object sender, System.EventArgs e)
{
CurrencyManager cm = (CurrencyManager)this.BindingContext[ds,"Books"];
if (cm.Position < cm.Count - 1)
{
cm.Position++;
}

}

4. Bài tập
Sử dụng Disconnected Architecture để làm lại bài tập ở Phần 1

×