简体   繁体   中英

How can I delete a selected DataGridView row from the database?

I have a Windows Forms form with DataGridView . The DataGridView has DataGridViewButtonColumn , and I have a database (id with autoincrement).

I can delete it from DataGridView .

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

How can I delete it from the database?

You should set your database's unique id as commandArgument to your cell button and when you call the delete command simply pass that id to remove that record from database.

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

Get value in backend:

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

and you can perform database delete on your button click event also.

You can use an SQL query to delete it from the database. Get a datagridview selected items and run a delete query like this:

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

I don't know which method are you using but you can delete it with LINQ like this:

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

northWind.Products.DeleteOnSubmit(deleteProduct);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM