自从我尝试编程以来已经有一段时间了。我一直在DGV和数据库上练习基本的CRUD。我的“ ADD / CREATE”功能正常运行,但删除似乎无效。

这是屏幕截图:

c# - 如何使用此方法删除数据库中的行?-LMLPHP


编辑:
在此处发布代码;这是我工作的添加/创建功能:

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();

    }

最佳答案

如果要删除按钮后的行,可以遵循此伪代码。


首先,您检查网格中是否选择了当前行,
如果找到一个,则从主
存储数据库表的键。 (这里我假设这个单元格
是该行中的第一个,并引用了
数据库表)
使用该数据打开连接,使用以下命令准备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();
    }
}

09-05 01:20
查看更多