簡體   English   中英

如何使用此方法刪除數據庫中的行?

[英]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();

    }

如果要刪除按鈕后的行,可以遵循此偽代碼。

  • 首先,您檢查網格中是否有當前行被選中,
  • 如果找到一個,則從存儲數據庫表主鍵的單元格中獲取值。 (在這里,我假設此單元格是行中的第一個單元格,並引用數據庫表中的列ID)
  • 使用該數據打開連接,准備帶有參數的DELETE命令,並調用ExecuteNonQuery來從數據庫表中刪除該行。
  • 之后,您可以從網格中刪除當前行,並通知基礎數據源該操作已完成。(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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM