[英]How do I delete a row in my database using this method?
自從我嘗試編程以來已經有一段時間了。 我一直在DGV和數據庫上練習基本的CRUD。 我的“ ADD / CREATE”功能正常運行,但刪除似乎無效。
這是屏幕截圖:
編輯:在這里發布代碼; 這是我工作的添加/創建功能:
private void btnAdd_Click(object sender, EventArgs e)
{
connectionstring = "server=" + server + ";" + "database=" + database +
";" + "uid=" + uid + ";" + "password=" + password + ";";
con = new MySqlConnection(connectionstring);
con.Open();
MySqlDataAdapter da = new MySqlDataAdapter("select * from testdatabase", con);
DataSet ds = new DataSet();
da.Fill(ds);
testTable1.DataSource = ds.Tables[0];
con.Close();
// now instead of these next 4 lines
DataRow row = ds.Tables[0].NewRow();
row[0] = tbID.Text;
row[1] = tbName.Text;
ds.Tables[0].Rows.Add(row);
// ds.Tables[0].Rows.RemoveAt(testTable1.CurrentCell.RowIndex);
// is what i used to delete
// what did i do wrong?
MySqlCommandBuilder cb = new MySqlCommandBuilder(da);
da.UpdateCommand = cb.GetUpdateCommand();
da.Update(ds);
((DataTable)testTable1.DataSource).AcceptChanges();
}
如果要刪除按鈕后的行,可以遵循此偽代碼。
之后,您可以從網格中刪除當前行,並通知基礎數據源該操作已完成。(AcceptChanges)
private void btnDelete_Click(object sender, EventArgs e) { // No row to delete? if(testTable1.CurrentRow == null) return; // Get the cell value with the primary key int id = Convert.ToInt32(testTable1.CurrentRow.Cells[0].Value) // Start the database work... connectionstring = .....; using(con = new MySqlConnection(connectionstring)) using(cmd = new MySqlCommand("DELETE FROM testdatabase where id = @id", con)) { con.Open(); cmd.Parameters.AddWithValue("@id", id); cmd.ExecuteNonQuery(); // Fix the grid removing the current row testTable1.Rows.Remove(testTable1.CurrentRow); // Fix the underlying datasource ((DataTable)testTable1.DataSource).AcceptChanges(); } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.