简体   繁体   中英

Gridview delete row from database

I want to to delete record(s) from table through C# gridview. The problem is that the rows are only getting deleted from gridview and not from table. I want to remove them from DB as well. here is my code.

private void Delete_Click(object sender, EventArgs e)
{
    if (this.dataGridView1.SelectedRows.Count > 0)
    {
        string  a = (string )this.dataGridView1.CurrentCell.Value;
            dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
        DeleteRecord(a);
    }

Now I want the definition of function DeleteRecord(a) its a humble request to give the code for this function which will obviously have the sql query so that i may delete the rows from table by getting the id of selected row.

It is rather impossible to tell the exact answer. Multiple ways:Let me show one.

1)Aspx page

<asp:GridView DataKeyNames="CategoryID" ID="GridView1" 
       runat="server" AutoGenerateColumns="False" 
       OnRowCommand="GridView1_RowCommand" 
       OnRowDataBound="GridView1_RowDataBound" 
       OnRowDeleted="GridView1_RowDeleted" OnRowDeleting="GridView1_RowDeleting">
  <Columns>
   <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
   <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
   <asp:TemplateField HeaderText="Select">
     <ItemTemplate>
       <asp:LinkButton ID="LinkButton1" 
         CommandArgument='<%# Eval("CategoryID") %>' 
         CommandName="Delete" runat="server">
         Delete</asp:LinkButton>
     </ItemTemplate>
   </asp:TemplateField>
  </Columns>
</asp:GridView>

2)Add rowdatabound event.

protected void GridView1_RowDataBound(object sender, 
                         GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1"); 
    l.Attributes.Add("onclick", "javascript:return " +
    "confirm('Are you sure you want to delete this record " +
    DataBinder.Eval(e.Row.DataItem, "CategoryID") + "')"); 
  }
}

3)And finally RowCommand:

protected void GridView1_RowCommand(object sender, 
                         GridViewCommandEventArgs e)
{
  if (e.CommandName == "Delete")
  {
    // get the categoryID of the clicked row
    int categoryID = Convert.ToInt32(e.CommandArgument);
    // Delete the record 
    DeleteRecordByID(categoryID);
    // Implement this on your own :) 
  }
}

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