You are on page 1of 8

Hng dn thc hnh Winforms vi C#

Chng 5: ADO.NET

CHNG 5 ADO.NET
T ng dng, ta c th kt ni v thao tc vi c s d liu bng 2 phng php sau: 1. Kt ni thng xuyn 2. Kt ni khng thng xuyn

Phn 1. Kt ni thng xuyn


1. Cc bc thc hin
Bc 1: S dng Connection kt ni n c s d liu Bc 2: Thit lp cu lnh thc thi: Insert, Select, Update, Delete Bc 3: Thc hin lnh M kt ni Thc thi cu lnh, x l d liu tr v ng kt ni

2. V d mu
Thit k giao din gm cc phn nh hnh sau:

Khi Load form cc d liu t bng Customers trong CSDL Northwind ca SQL Server 2000 s c hin th trn ListView v DataGridView Khi chn 1 dng trn ListView hoc DataGridView, d liu ca dng tng ng s hin th trn cc TextBox Khi click vo nt Insert, d liu trong cc Textbox c thm vo c s d liu Khi click vo nt Update, record c chn s c chnh sa v cp nht vo CSDL Khi click nt Delete, record c chn s b xa khi CSDL

Hng dn thc hnh Winforms vi C#

Chng 5: ADO.NET

V d 1: c d liu t bng Customers trong CSDL Northwind ca SQL Server 2000 v hin th ln ListView v DataGridView
// 1. Thit lp kt ni string strConn = "server=.; Database = Northwind; uid=sa; pwd=;"; SqlConnection cnNorth = new SqlConnection(strConn); // 2. Thit lp cu lnh string sqlSelect = "select CustomerID, CompanyName, Address, City from Customers"; SqlCommand cmdNorth = new SqlCommand(sqlSelect, cnNorth); cmdNorth.Connection.Open(); // 3. Thc hin lnh SqlDataReader reader = cmdNorth.ExecuteReader();
// Ly d liu hin th, x l... qua i tng Reader // Xem v d 1.1 hoc v d 1.2 // // ng kt ni cmdNorth.Connection.Close();

V d 1.1: on chng trnh sau m t vic c d liu t i tng reader v hin th ln 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: on chng trnh sau m t vic c d liu t i tng reader v hin th ln 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);

Hng dn thc hnh Winforms vi C#


}

Chng 5: ADO.NET

dataGridView1.DataSource = list;

V d 1.3: CustomerInfo l lp m t cc thng tin v i tng Customer. CustomerInfo c vit 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: Ly d liu t cc Textbox: txtID, txtName, txtddress v txtCity lu vo Database v cp nht mi d liu hin th trn form
private void cmdInsert_Click(object sender, System.EventArgs e) { // 1. Kt ni string strConn = "server=(local); Database = Northwind; uid=sa; pwd=;"; SqlConnection cnNorth = new SqlConnection(strConn); // 2. Thit t cu lnh thc 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;

Hng dn thc hnh Winforms vi C#


cmdNorth.Parameters[3].Value = txtCity.Text; // 3. Thc thi lnh cmdNorth.Connection.Open(); int kq = cmdNorth.ExecuteNonQuery(); if (kq > 0) { MessageBox.Show("D liu cp nht!"); // Gi li hm Load d liu V d 1 } else { MessageBox.Show("C li xy ra!"); } cmdNorth.Connection.Close(); }

Chng 5: ADO.NET

V d 3: Chn 1 dng trn ListView d liu tng ng s hin 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 liu sau khi hiu chnh trn TextBox vo CSDL


private void cmdUpdate_Click(object sender, System.EventArgs e) { if (lsvCustomer.SelectedItems.Count == 0) return; // Ly thng tin v i tng ang c chn CustomerInfo old = lsvCustomer.SelectedItems[0].Tag as CustomerInfo; // Ly thng tin sau khi chnh sa CustomerInfo cm = new CustomerInfo(txtID.Text, txtName.Text, txtAddress.Text, txtCity.Text); // 1. i tng kt ni string strConn = "server=(local); Database = Northwind; uid=sa; pwd=;" SqlConnection cnNorth = new SqlConnection(strConn); // 2. Cu lnh thc 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. Thc thi lnh cmdNorth.Connection.Open(); int kq = cmdNorth.ExecuteNonQuery(); if (kq > 0) { MessageBox.Show("Cp nht thnh cng!"); //Gi li phng thc Load d liu V d 1 } else

Hng dn thc hnh Winforms vi C#


MessageBox.Show("Li!"); cmdNorth.Connection.Close(); }

Chng 5: ADO.NET

V d 5: Xa dng c chn
private void cmdDelete_Click(object sender, System.EventArgs e) { if (lsvCustomer.SelectedItems.Count == 0) return; // Ly thng tin v i tng ang c chn CustomerInfo cm = lsvCustomer.SelectedItems[0].Tag as CustomerInfo; // 1. i tng kt ni string strConn = "server=(local); Database = Northwind; uid=sa; pwd=;" SqlConnection cnNorth = new SqlConnection(strConn); // 2. Cu lnh thc 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. Thc thi lnh cmdNorth.Connection.Open(); int kq = cmdNorth.ExecuteNonQuery(); if (kq > 0) { MessageBox.Show("Cp nht thnh cng!"); //Gi li phng thc Load d liu V d 1 } else MessageBox.Show("Li!"); cmdNorth.Connection.Close(); }

3. Bi tp
Bi 1: Thit k CSDL v Xy dng ng dng qun l thng tin khch hng vi cc yu cu sau: - Form ng nhp: ng nhp trc khi s dng ng dng

Kim tra d liu rng trc khi thc hin vic x l ng nhp Nu ng nhp thnh cng th cho php s dng phn Qun l

Form Qun l: c giao din nh hnh bn di, form ny xem, thm, sa, xa thng tin ca khch hng. Cc thng tin cn qun l bao gm: m s, h tn, ngy sinh, a ch, in thoi, email, hnh nh o Thng tin khch hng s hin th ngay khi vo form Qun l o Thm mi: thm mi 1 khch hng vo CSDL o Cp nht: Chnh sa thng tin 1 khch hng trong CSDL o Xa: Xa thng tin mt khch hng

Hng dn thc hnh Winforms vi C#

Chng 5: ADO.NET

Phn 2. Kt ni khng thng xuyn (Disconnected Architecture)


1. Cc bc thc hin Bc 1: S dng Connection kt ni n c s d liu Bc 2: To i tng DataSet Bc 3: To i tng DataAdapter v cc cu lnh thc thi trn d liu Bc 4: d liu vo DataSet Bc 5: Tng tc, x l d liu trn DataSet Bc 6: Lu vo CSDL 2. V d mu

Hng dn thc hnh Winforms vi 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);
//To cc cu lnh 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;

Hng dn thc hnh Winforms vi 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. Mt s on code mu
// 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 tp
S dng Disconnected Architecture lm li bi tp Phn 1

You might also like