我有2列是名稱和價格。 假設數據庫表中已經有一些數據將顯示在datagridview中。 現在,當用戶輸入新的數據行時(無論有多少行),並且他們點擊保存按鈕,所有新行數據將被保存到數據庫中。c#sql datagridview如何只插入新的數據行到數據庫
問題是, 我該如何捕獲新的數據行?或者如何檢查名稱是否存在,檢查價格是否相同,然後不插入,如果價格不同,則更新價格。
這裏是我的代碼:
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=tcp:SHEN-PC,49172\\SQLEXPRESS;Initial Catalog=LSEStock;Integrated Security=True";
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
for (int i = 0; i<dataGridView1.Rows.Count; i++)
{
String insertData = "INSERT INTO CostList(SupplierName, CostPrice, PartsID) VALUES (@SupplierName, @CostPrice, @PartsID)" ;
SqlCommand cmd = new SqlCommand(insertData, con);
cmd.Parameters.AddWithValue("@SupplierName", dataGridView1.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("@CostPrice", dataGridView1.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("@PartsID", textBox1.Text);
da.InsertCommand = cmd;
cmd.ExecuteNonQuery();
}
con.Close();
編輯:上面的代碼將在DataGridView添加的每個數據到數據庫,並不斷重複。
感謝您的關注。
你能否提供一些示例代碼供我參考?或一些鏈接,謝謝 – 2012-08-11 00:53:45
試試這個http://technico.qnownow.com/how-to-insert-update-delete-rows-in-asp-net-gridview-control/ – 2012-08-13 09:09:07