Sie sind auf Seite 1von 11

ADO.

NET
THAO TC CSDL ADO.NET V I DATAGRIDVIEW
string sqlquery = "SELECT * FROM EMPLOYEES"; string sqlConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\SQL Server 2000 Sample Databases\\NORTHWND.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True"; SqlConnection conn = new SqlConnection(sqlConnectionString); SqlCmdmand cmd = new SqlCmdmand(sqlQuery, conn); SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); DataTable dt = new DataTable(); try { conn.Open(); adapter.Fill(ds); dt = ds.Tables[0]; dataGridView1.DataSource = dt; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); }

CCH DUY T CC ROW, COLUMN TRONG DataTable


foreach (DataRow row in dt.Rows) { foreach (DataColumn col in dt.Columns) { // Lm g y y :D } }

THAO TC CSDL ADO.NET V I LISTVIEW


string sqlquery = "SELECT * FROM EMPLOYEES"; string sqlConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\SQL Server 2000 Sample Databases\\NORTHWND.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True"; SqlConnection conn = new SqlConnection(sqlConnectionString); SqlCmdmand cmd = new SqlCmdmand(sqlQuery, conn); SqlDataReader dr; ListViewItem item1; // Thao tc v i Listview listView1.Clear(); listView1.Columns.Add("Frist Name", 40); listView1.Columns.Add("Last Name", 40); listView1.Columns.Add("Position Name", 40); listView1.View = View.Details; try { conn.Open(); dr = cmd.ExecuteReader(); while (dr.Read()) { item1 = new ListViewItem(dr[1].ToString()); item1.SubItems.Add(dr[2].ToString()); item1.SubItems.Add(dr[3].ToString()); listView1.Items.Add(item1); } dr.Close(); dr.Dispose(); } catch(Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); }

L Y CC THNG TIN PROPERTY C A SqlConnection


string sqlConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\SQL Server 2000 Sample Databases\\NORTHWND.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True"; SqlConnection conn = new SqlConnection(sqlConnectionString); try { conn.Open(); label1.Text = "CONNECTION OPENED" + "\n\n CONNECTION PROPERTIES:" + "\n\t Connection string: " + conn.ConnectionString + "\n\n\t Connection Database: " + conn.Database + "\n\n\t Connection DataSource: " + conn.DataSource + "\n\n\t Connection State: " + conn.State + "\n\n\t Connection WorkStationID: " + conn.WorkstationId; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); label1.Text += " CONNECTION CLOSED"; }

TH C THI CU TRUY V N

N CSDL

string sqlConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\SQL Server 2000 Sample Databases\\NORTHWND.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True"; string sqlQuery = "SELECT FIRSTNAME, LASTNAME FROM EMPLOYEES"; //string sqlQuery = "SELECT COUNT(*) FROM EMPLOYEES"; SqlConnection conn = new SqlConnection(sqlConnectionString); SqlCommand cmd = new SqlCommand(sqlQuery, conn); SqlDataReader dr; try { conn.Open(); dr = cmd.ExecuteReader(); while (dr.Read()) { label1.Text = "K T QU : " + dr[0].ToString() + " " + dr[1].ToString(); } dr.Close(); } catch (SqlException ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); }

L Y THAY

IC AD

LI U TRN DataGridView B NG DataSet

DataSet dsChange = new DataSet("Changed"); try { dsChange = ds.GetChanges(); if (dsChange != null) this.dataGridView2.DataSource = dsChange.Tables[0]; else this.dataGridView2.DataSource = null; } catch (Exception ex) { MessageBox.Show(ex.Message); }

DataSet, DataTable
// t tn cho DataSet DataSet ds = new DataSet("EMPLOYEES"); // L y tn c a DataSet string s = ds.DataSetName; // Thm table vo DataSet ds.Tables.Add(new DataTable("EMPLOYEES")); // L y tn DataTable DataTable dt = new DataTable("EMPLOYEES"); string s = dt.TableName; // L y t ng s table trong DataSet int i = dataSet.Tables.Count; // L y s l ng dng trong 1 table int i = dataSet.Tables[0].Rows.Count; // L y s l ng c t trong 1 table int i = dataSet.Tables[0].Columns.Count; // Ch p nh n cc s thay ds.AcceptChanges(); // Khng ch p nh n cc s ds.RejectChanges(); // Xa tr ng cc CSDL ds.Clear(); // Ghi d li u ra file XML ds.WriteXml("D:\\TestXML.xml"); // c d li u t file XML ds.ReadXml("D:\\TestXML.xml"); i d thay li u t i d pha ng i dng i dng

li u t

pha ng

PHN BI T CASE SENSITIVE


string strSQL = "SELECT * FROM CUSTOMERS"; string dtName = ""; Con.Open(); SqlDataAdapter da = new SqlDataAdapter(strSQL, Con); DataSet ds = new DataSet("Customers"); ds.CaseSensitive = true; da.Fill(ds, "Customers"); // Query th 2 strSQL = "select * from Orders"; da = new SqlDataAdapter(strSQL, Con); DataTable dt = new DataTable(); da.Fill(dt); // Thm m t table m i vo ds.Tables.Add(dt); ds.Dispose(); // a d li u ra dng foreach duy t cc table a vo foreach (DataTable dataTable in ds.Tables) { dtName += dataTable.TableName + ""; } if (dtName == "Orders") { label1.Text = "Case Sensitive"; dataGridView1.DataSource = ds.Tables[0]; } else label1.Text = "Case Sentive False"; Con.Close();

Load d li u b ng DataTable
string sqlquery = "SELECT TOP 10 * FROM EMPLOYEES"; dt = new DataTable("EMPLOYEES"); try { SqlDataAdapter da = new SqlDataAdapter(sqlquery,Connection.sqlConnection); da.Fill(dt); da.Dispose(); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } dataGridView1.DataSource = dt; label1.Text = dt.TableName;

T o m i DataTable v thm vo cc column


dt = new DataTable("SinhVien"); try { dt.Columns.Add("StID", System.Type.GetType("System.Double")); dt.Columns.Add("StudentName", System.Type.GetType("System.String")); dt.Columns.Add("Class", System.Type.GetType("System.String")); dt.Columns.Add("Subject", System.Type.GetType("System.String")); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } dataGridView1.DataSource = dt;

Thm row vo DataTable c s n:


object[] obj = new object[4] { 081101, "T", "0811A", "Winform" }; dt.Rows.Add(obj); obj = new object[4] { 091103, "To", "091102A", "Webform" }; dt.Rows.Add(obj);

Copy m t DataTable c s n:
DataTable dtClone = new DataTable(); try { dtClone = dataTable.Clone(); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } dataGridView2.DataSource = dtClone;

L u : ph ng th c Clone() ch l copy c u trc c a 1 table, ch khng copy h t cc d li u c trong table . N u mu n thm d li u vo th dng ph ng th c ImportRow() :D

Thm d li u vo table sau khi Clone:


DataTable dtClone = new DataTable(); try { dtClone = dt.Clone(); for (int i = 0; i < dataTable.Rows.Count; i++) { // Dng ph ng th c ImportRow() a d li u vo dtClone.ImportRow(dt.Rows [i] ); } // Thm dng Cu t ny vo phn bi t gi a dtClone v dt object[] obj = new object[4] { 08110, "Cu t", "08110A", "Winform" }; dtClone.Rows.Add(obj); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } dataGridView2.DataSource = dtClone;

L c d li u trong DataView
DataTable dt =cls.FillDataTable("SELECT * FROM EMPLOYEES", CommandType.Text); DataView dv = new DataView(dt); if (textBox1.Text != "")// L c theo t kha c trong textbox1 { string strFilter = "FirstName like '%" + textBox1.Text + "%'"; strFilter += " or LastName like '%" + textBox1.Text + "%'"; dv.RowFilter = strFilter; } label1.Text = "Number of Employee(s): " + dv.Count.ToString(); dataGridView1.DataSource = dv;

Sort cc column trong DataView


DataTable dt=cls.FillDataTable("SELECT * FROM EMPLOYEES ", CommandType.Text); DataView dv = new DataView(dt); dataView.Sort = "FirstName ASC";//DESC l s p gi m //mu n s p x p nhi u c t th lm nh sau: //dv.Sort = "FirstName ASC, LastName DESC"; dataGridView1.DataSource = dv;

Thm m i record trong DataView


DataTable dt= cls.FillDataTable("SELECT * FROM REGION", CommandType.Text); DataView dv = new DataView(dt); if (textBox2.Text != "") { DataRowView rowView = dv.AddNew(); rowView["RegionID"] = textBox2.Text; rowView["RegionDescription"] = textBox3.Text; rowView.EndEdit(); } dataGridView1.DataSource = dv;

Delete record trong DataView


DataTable dt= cls.FillDataTable("SELECT * FROM Employees", CommandType.Text); DataView dv = new DataView(dt); try { dv.Delete(2); } catch (Exception ex) { MessageBox.Show(ex.Message); } dataGridView1.DataSource = dv;

L y dng() hi n t i trong DatagridView xu t ra label1, gi s table trong DatagridView c 3 c t


//L y dng hi n t i trong DatagridView DataGridViewRow dgvRow = dataGridView1.CurrentRow; label1.Text = " " + Convert.ToString(dgvRow.Cells[0].Value) + "---" + Convert.ToString(dgvRow.Cells[1].Value) + "---"+ Convert.ToString(dgvRow.Cells[2].Value); //L y hi n t i trong DatagridView DataGridViewCell dgvCell = dataGridView1.CurrentCell; label1.Text = " " + Convert.ToString(dgvCell.Value);

Load d li u ln combobox trong DatagridView


DataTable dtComBo = cls.FillDataTable("select City from Customers", CommandType.Text); DataTable dt = cls.FillDataTable("select CustomerID, CompanyName, City from Customers", CommandType.Text); City.DataSource = dtComBo; City.DisplayMember = "City"; City.ValueMember = "City"; dataGridView1.DataSource = dt;

T o button trong DatagridView v xc

nh button

c nh n

DataTable dt = cls.FillDataTable("select CustomerID, CompanyName,City from Customers", CommandType.Text); dataGridView1.DataSource = dt; foreach (DataGridViewRow dgRow in dataGridView1.Rows) { dgRow.Cells[0].Value = "Accept"; dgRow.Cells[1].Value = "Cancel"; } // dng Event CellClick c a DataGirdView xc nh nt c nh n private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { switch (e.ColumnIndex) { case 0: // khi duoc nhan se hien ra Vi du Accept v 2 l s c t s hi n thi MessageBox.Show("Vi du Accept: " + Convert.ToString(dataGridView1[2, e.RowIndex].Value)); break; case 1: MessageBox.Show("Vi du Cancel: " + Convert.ToString(dataGridView1[2, e.RowIndex].Value)); break; } }

Thm m t record vo DataSet dng SqlCommandBuilder


string sqlquery = "select LastName,FirstName,Title,BirthDate from Employees"; ds = new DataSet("Employees"); try { da = new SqlDataAdapter(sqlquery, Connection.sqlConnection); da.Fill(ds); SqlCommandBuilder sqlComB = new SqlCommandBuilder(da); // Thm 1 record m i vo DataRow r = ds.Tables[0].NewRow(); r["FirstName"] = textBox1.Text; r["LastName"] = textBox1.Text; r["Title"] = textBox2.Text; r["BirthDate"] = dateTimePicker1.Text; ds.Tables[0].Rows.Add(r); da.Update(ds); MessageBox.Show("Thm thnh cng.", "V d ", MessageBoxButtons.OK, MessageBoxIcon.Information); Form1_Load(null, null); da.Dispose(); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); }

Das könnte Ihnen auch gefallen