You are on page 1of 8

H ng d n th c hnh Winforms v i C#

Chng 5: ADO.NET

CHNG 5 ADO.NET
T ng d ng, ta c th k t n i v thao tc v i c s d li u b ng 2 phng php sau: 1. K t n i th ng xuyn 2. K t n i khng th ng xuyn

Ph n 1. K t n i th ng xuyn
1. Cc 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 cu l nh th c thi: Insert, Select, Update, Delete B c 3: Th c hi n l nh M k tn i Th c thi cu 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 cc ph n nh hnh sau:

Khi Load form cc d li u t b ng Customers trong CSDL Northwind c a SQL Server 2000 s c hi n th trn ListView v DataGridView Khi ch n 1 dng trn ListView ho c DataGridView, d li u c a dng tng ng s hi n th trn cc TextBox Khi click vo nt Insert, d li u trong cc Textbox c thm vo c s d li u Khi click vo nt Update, record c ch n s c ch nh s a v c p nh t vo CSDL Khi click nt Delete, record c ch n s b xa kh i CSDL Trang 1

Hue-Aptech | Tr n Vn Long Email: tvlongsp@gmail.com

H ng d n th c hnh Winforms v i C#

Chng 5: ADO.NET

V d 1: c d li u t b ng Customers trong CSDL Northwind c a SQL Server 2000 v hi n th ln 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 cu 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 // Xem v d 1.1 ho c v d 1.2 // // ng k t n i cmdNorth.Connection.Close(); i t ng Reader

V d 1.1: ListView

o n chng trnh sau m t vi c

c d li u t

i t ng reader v hi n th ln

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 chng trnh sau m t vi c DataGridView


ArrayList list = new ArrayList();

c d li u t

i t ng reader v hi n th ln

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);

Hue-Aptech | Tr n Vn Long Email: tvlongsp@gmail.com

Trang 2

H ng d n th c hnh Winforms v i C#
}

Chng 5: ADO.NET

dataGridView1.DataSource = list;

V d 1.3: CustomerInfo l l p m t cc thng tin v c vi t nh sau:

i t ng Customer. CustomerInfo

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 cc Textbox: txtID, txtName, txt ddress v txtCity v c p nh t m i d li u hi n th trn form

lu vo Database

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 cu 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;

Hue-Aptech | Tr n Vn Long Email: tvlongsp@gmail.com

Trang 3

H ng d n th c hnh Winforms v i C#
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 hm Load d li u V d 1 } else { MessageBox.Show("C l i xy ra!"); } cmdNorth.Connection.Close(); }

Chng 5: ADO.NET

V d 3: Ch n 1 dng trn ListView d li u tng ng s hi n th trn cc 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: Lu d li u sau khi hi u ch nh trn TextBox vo CSDL


private void cmdUpdate_Click(object sender, System.EventArgs e) { if (lsvCustomer.SelectedItems.Count == 0) return; // L y thng tin v i t ng ang c ch n CustomerInfo old = lsvCustomer.SelectedItems[0].Tag as CustomerInfo; // L y thng 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. Cu 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 thnh cng!"); //G i l i phng th c Load d li u V d 1 } else

Hue-Aptech | Tr n Vn Long Email: tvlongsp@gmail.com

Trang 4

H ng d n th c hnh Winforms v i C#
MessageBox.Show("L i!"); cmdNorth.Connection.Close(); }

Chng 5: ADO.NET

V d 5: Xa dng c ch n
private void cmdDelete_Click(object sender, System.EventArgs e) { if (lsvCustomer.SelectedItems.Count == 0) return; // L y thng 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. Cu 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 thnh cng!"); //G i l i phng th c Load d li u V d 1 } else MessageBox.Show("L i!"); cmdNorth.Connection.Close(); }

3. Bi t p
Bi 1: Thi t k CSDL v Xy d ng ng d ng qu n l thng tin khch hng v i cc yu c u sau: - Form ng nh p: ng nh p tr c khi s d ng ng d ng

Ki hi N s

m tra d li u r ng tr c khi th c n vi c x l ng nh p u ng nh p thnh cng th cho php d ng ph n Qu n l

Form Qu n l: c giao di n nh hnh bn d i, form ny xem, thm, s a, xa thng tin c a khch hng. Cc thng tin c n qu n l bao g m: m s , h tn, ngy sinh, a ch , i n tho i, email, hnh nh o Thng tin khch hng s hi n th ngay khi vo form Qu n l o Thm m i: thm m i 1 khch hng vo CSDL o C p nh t: Ch nh s a thng tin 1 khch hng trong CSDL o Xa: Xa thng tin m t khch hng

Hue-Aptech | Tr n Vn Long Email: tvlongsp@gmail.com

Trang 5

H ng d n th c hnh Winforms v i C#

Chng 5: ADO.NET

Ph n 2. K t n i khng th ng xuyn (Disconnected Architecture)


1. Cc 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 cc cu l nh th c thi trn d li u B c 4: d li u vo DataSet B c 5: Tng tc, x l d li u trn DataSet B c 6: Lu vo CSDL 2. V d m u

Hue-Aptech | Tr n Vn Long Email: tvlongsp@gmail.com

Trang 6

H ng d n th c hnh Winforms v i C#

Chng 5: ADO.NET

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 cc cu 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;

Hue-Aptech | Tr n Vn Long Email: tvlongsp@gmail.com

Trang 7

H ng d n th c hnh Winforms v i C#
txtTitle.Enabled = true; txtAuthor.Enabled = true; txtPublisher.Enabled = true; txtPrice.Enabled = true; } private void cmdSave_Click(object sender, EventArgs e) { objDa.Update(ds,"Books"); } }

Chng 5: ADO.NET

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. Bi t p
S d ng Disconnected Architecture lm l i bi t p Ph n 1

Hue-Aptech | Tr n Vn Long Email: tvlongsp@gmail.com

Trang 8

You might also like