How to create a delete button in GridView?

I made another Column in my GridView called delete. When delete is clicked, the row should be deleted or in other words, I need to get the current row’s user name to delete it.

  1. Which event should I use? (RowDeleting, Rowdeleted etc…)
  2. How do I get the username from the current row?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Here is a great article about typical usages of DataGrid.

Enjoy.

Method 2

You can use the RowDeleting event, by storing the user name in the data key collection you can access it programmatically.

<asp:GridView DataKeyNames="UserName" ID="GridView1" 
     runat="server" OnRowDeleting="GridView1_RowDeleting">

Then, in the code behind use the data key to delete the record.

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
  string userName = (string) GridView1.DataKeys[e.RowIndex].Value;
  DeleteUser(userName); 
}

Method 3

1:-

protected void grdLst_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

    int i = Convert.ToInt32(grdLst.DataKeys[e.RowIndex].Value);
    ob.DeleteCoverage(i);
    Response.Redirect("fullcoverage.aspx");
}

2:-

    GridViewRow row = (GridViewRow)grdlist.Rows[e.RowIndex];
    string name = row.Cells[1].Text;
    Response.Write(name.Trim());

Method 4

tablename.Rows.RemoveAt(datagrid1.currentcell.rowindex);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x