C#.net删除dataGridView中选中行并同时更新数据库
??????? {
?????????????SqlConnection conn = new SqlConnection("數(shù)據(jù)庫連接串");
?????????????conn.Open();
?????????????SqlDataAdapter daAuthors = new SqlDataAdapter("Select * From student", conn);
?????????????DataSet dsPubs = new DataSet("Pubs");
?????????????daAuthors.FillSchema(dsPubs, SchemaType.Source, "student"); //FillSchema加載表的架構(gòu)和數(shù)據(jù),有了架構(gòu),表就知道哪個列是它的主鍵,同時 Rows 集合的 Find 方法也就可用了。
?????????????daAuthors.Fill(dsPubs, "student");
?????????????DataTable tblAuthors;
?????????????tblAuthors = dsPubs.Tables["student"];
??????????? if (MessageBox.Show("確實要刪除該行嗎?", "詢問", MessageBoxButtons.YesNo) == DialogResult.Yes)
??????????? {
????????????????DataRow drCurrent;??????????????
????????????????string Row_zhi = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();//獲取第一個單元格的值????????????
??????????????? //MessageBox.Show(Row_zhi);???????????
??????????????? drCurrent = tblAuthors.Rows.Find(Row_zhi);
????????????????drCurrent.Delete();
??????????????? SqlCommandBuilder objCommandBuilder = new SqlCommandBuilder(daAuthors); //SqlCommandBuilder 提供自動生成單表命令的一種方式,這些命令用于協(xié)調(diào)使用關(guān)聯(lián)的 SQL Server 數(shù)據(jù)庫對 DataSet 執(zhí)行的更改。??????????????
????????????????daAuthors.Update(dsPubs, "student"); //數(shù)據(jù)適配器.Update()方法????????????????
??????????????? //MessageBox.Show("數(shù)據(jù)庫更新成功!");
????????????????//-------重新綁定dataGridView的數(shù)據(jù)源,以便重新顯示-------
??????????????? daAuthors.Fill(dsPubs, "student");
??????????????? DataTable tblAuthors1;
??????????????? tblAuthors1 = dsPubs.Tables["student"];
??????????????? dataGridView1.DataSource = tblAuthors1;
??????????? }
??????????? conn.Close();
??????????? conn.Dispose();
??????????? //MessageBox.Show("數(shù)據(jù)庫連接已關(guān)閉");????????????
??????? }
注:
SqlDataAdapter 不自動生成協(xié)調(diào)對 DataSet 執(zhí)行的更改(使用關(guān)聯(lián)的 SQL Server 實例)所需的 Transact-SQL 語句。但是,如果設置了 SqlDataAdapter 的 SelectCommand 屬性,則可以創(chuàng)建一個 SqlCommandBuilder 對象來自動生成用于單表更新的 Transact-SQL 語句。然后,SqlCommandBuilder 將生成其他任何未設置的 Transact-SQL 語句。
一旦設置 DataAdapter 屬性,SqlCommandBuilder 就將其自身注冊為 RowUpdating 事件的偵聽器。一次只能將一個 SqlDataAdapter 與一個 SqlCommandBuilder 對象(或相反)互相關(guān)聯(lián)。
為了生成 INSERT、UPDATE 或 DELETE 語句,SqlCommandBuilder 會自動使用 SelectCommand 屬性來檢索所需的元數(shù)據(jù)集。如果在檢索元數(shù)據(jù)后(例如在第一次更新后)更改 SelectCommand,則應調(diào)用 RefreshSchema 方法來更新元數(shù)據(jù)。
SelectCommand 還必須至少返回一個主鍵列或唯一的列。如果什么都沒有返回,就會產(chǎn)生 InvalidOperation 異常,不生成命令。
SqlCommandBuilder 還使用由 SelectCommand 引用的 Connection、CommandTimeout 和 Transaction 屬性。如果修改了任何這些屬性或者替換了 SelectCommand 本身,用戶則應調(diào)用 RefreshSchema。否則,InsertCommand、UpdateCommand 和 DeleteCommand 屬性將保留它們以前的值。
如果調(diào)用 Dispose,則會解除 SqlCommandBuilder 與 SqlDataAdapter 的關(guān)聯(lián),并且不再使用所生成的命令。
轉(zhuǎn)載于:https://www.cnblogs.com/Garden-blog/archive/2011/04/10/2011668.html
與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的C#.net删除dataGridView中选中行并同时更新数据库的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在SharePoint 2010系统中安
- 下一篇: php设置内存