【问题标题】:How can I delete a selected DataGridView row from the database?如何从数据库中删除选定的 DataGridView 行?
【发布时间】:2019-04-04 10:05:02
【问题描述】:

我有一个带有DataGridView 的 Windows 窗体表单。 DataGridView 有 DataGridViewButtonColumn,我有一个数据库(id 自动递增)。

我可以从DataGridView删除它。

private void dgv_CellContentClick(object sender, DataGridViewCellEventArgs e) {
   if (e.ColumnIndex == Delete.Index) {
      dgv.Rows.Remove(dgv.Rows[e.RowIndex]);
   }
}

如何从数据库中删除它?

【问题讨论】:

  • 到底是什么问题?你试过什么?您使用的是 OR 映射器吗?
  • 您是否使用数据表作为数据源?然后从表中删除。

标签: c# sql-server winforms


【解决方案1】:

您应该将数据库的唯一 ID 设置为 commandArgument 到您的单元格按钮,当您调用删除命令时,只需传递该 ID 即可从数据库中删除该记录。

<asp:Button ID="btnCellDelete" runat="server" CommandArgument = "<%# Eval("DB_ID")%>" Text="Delete Row" />

在后端获取价值:

var item = (Button)e.Row.DataItem;
var dbID  = item.CommandArgument.ToStrng();

你也可以在你的按钮点击事件上执行数据库删除。

【讨论】:

    【解决方案2】:

    您可以使用 SQL 查询将其从数据库中删除。获取 datagridview 选定项并运行如下删除查询:

    int id= this.dataGridView1.SelectedItems[0].Text;
    
    con.Open();
    cmd.Connection = con;
    cmd.Parameters.Clear();
    cmd.Parameters.AddWithValue("@id", id);
    cmd.CommandText = "delete from data where id=@id";
    cmd.ExecuteNonQuery();
    

    我不知道您使用的是哪种方法,但您可以使用 LINQ 将其删除,如下所示:

    Product deleteProduct = northWind.Products.First(u => u.ProductID == id);
    
    northWind.Products.DeleteOnSubmit(deleteProduct);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多