GridView Confirm When Delete
By AzamSharp
Views: 25651

Introduction:

Everyone likes a confirmation that let them know that what record is being deleted. In this article I will show you how you can prompt confirmation boxes when you delete a record from the GridView control.

Implementing the Confirmation Feature:

The first thing that you need to do is to attach the JavaScript confirmation code to the delete column of the GridView control. This can be done in the Row_DataBound event of the GridView control. Row_DataBound event is fired whenever the row is attached to the GridView. Hence this is fired when the GridView is building for the first time or even when the page is reloaded.

Let's see the HTML part of the GridView code:

<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>

 

As you can see from the above code that I have three columns in the GridView. Columns CategoryID and CategoryName are the bound columns and the column Delete is a template column. The command argument is set as the CategoryID which means that whenever the LinkButton is clicked it will pass CategoryID as an argument. The CommandName is set to "Delete".

The CommandName property is very important. If you have a LinkButton or a Button control inside the template column of the GridView control and the CommandName property is set to "Delete" then apart from GridView_RowCommand event the GridView_Row_Deleting event is also fired.

Now, let's see the GridView_RowBound event where I attach the JavaScript code to every LinkButton.

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") + "')");

}

}

In the above code I checked that whether the GridView row is a DataRow and if it was I simply attached some JavaScript code using the Attributes.Add method.

Catching the Primary Key of the Clicked Row:

Now, that you have successfully attached JavaScript code to the GridView control all that is left if to catch the primary key of the row which you have clicked so that you can perform further operations (like deleting the row). Remember what I said about a LinkButton or a Button control with CommandName set to "Delete". If you don't read the text in the box again.

The CommandName property is very important. If you have a LinkButton or a Button control inside the template column of the GridView control and the CommandName property is set to "Delete" then apart from GridView_RowCommand event the GridView_Row_Deleting event is also fired.

Now, since our LinkButton commandName is set to Delete that means we have two choices of getting the primary key from the Gridview. We can do this in the RowCommand event or we can do this in the Row_Deleting event. I am going to show you both of them.

Catching the primary key in the RowCommand event:

This is pretty simple all you need to do is to get the value from the CommandArgument property which you have already set to the CategoryID.

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

{

if (e.CommandName == "Delete")

{

int categoryID = Convert.ToInt32(e.CommandArgument); // get the categoryID of the clicked row

// Delete the record

DeleteRecordByID(categoryID); // Implement this on your own :)

}

}

 

e.CommandArgument returns object so you need to convert it to integer as I have done above.

Catching the primary key in the Row_Deleting event:

Let's see how we can catch the primary key of the clicked row in the Row_Deleting event.

<asp:GridView DataKeyNames="CategoryID" ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound"

 OnRowDeleted="GridView1_RowDeleted" OnRowDeleting="GridView1_RowDeleting">

 

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

int categoryID = (int) GridView1.DataKeys[e.RowIndex].Value;

DeleteRecordByID(categoryID);

}

In the above technique you must set the DataKeyNames property of the GridView to "CategoryID". GridView1.DataKeys[e.RowIndex].Value preperty gets the CategoryID out of the row which is clicked.

Using the ClientOnClick attribute:

This method was submitted by AM Brain.

<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="LinkBtnDelete" runat="server"
OnClientClick="return confirm('OK to Delete?');"
CommandName="Delete">Delete
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>

I have attached the source code files with this project so please free to download them.

I hope you liked this article, happy coding!

If you are one of those thousands of people who are benefited from GridViewGuy articles and want to show your love then you will be interested in giving a donation.

Make a Donation

Once, again thank you very much and remember its because of you FINE people that this website is up and running.

 

Export Button is a custom control that let's you export your DataGrid or TextBox data to several different formats. The control is extremely easy to use and also exposes design time features. In this article I will discuss some of the features of the Export Button and how it benefits the developer.

BUY IT NOW

 

 

By AzamSharp




Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: Datakeynames
Name: William
Date: 2/15/2007 3:42:02 AM
Comment:
Hi,

Is there any way to have a child object as a datakeyname.

i.e. my datakeyname needs to read object1.ID where object1 is a child object of the gridview datasource object.
Subject: GridView Confirm When Delete
Name: Madhu Menon
Date: 3/19/2007 3:03:13 AM
Comment:
hi..its nice to have someone helping everyone. Its nice and easy code..Keep up.

Cheers
Mady
Subject: confirm when delete
Name: pepero
Date: 3/28/2007 1:52:48 AM
Comment:
Nice!! thx
Subject: Catching the primary key in the Row_Deleting event
Name: shahir
Date: 4/25/2007 4:10:23 AM
Comment:
I tried to implement the method, but it's not working and it prompts error msg: Specified cast is not valid

Subject: RE: shahir
Name: AzamSharp
Date: 4/25/2007 8:35:51 AM
Comment:
Hi Shahir,

Can you paste some code please?
Subject: Question
Name: Csharplearner
Date: 5/2/2007 2:08:40 PM
Comment:
Good Article. But I do have a Question.In scenarios like shopping cart where the shopper will NOT be deleting from the backend database but rather would be able to delete a product from shoppingcart ->how do you delete a row from an unbound GridView?

In my ShoppingCart The GridView is getting populated from Product.aspx page GridView based on the selection by the shopper.
Any suggestions as to how to go about?
Subject: GridView deleting a row
Name: Roxid
Date: 5/27/2007 12:26:41 AM
Comment:
Hi ;
I couldnt use this line coz my Id s Type Is Long!
DeleteRecordByID(ID);

can pls u help me on this?

Heres my code:


 























****
public partial class General_AddSection3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LibraryManager.ConnectionString = "Provider=sqloledb;Data Source=172.16.1.107;Initial Catalog=Library;User Id=safari;Password=sharlktale;";

}

protected void Button1_Click(object sender, EventArgs e)
{
GridView1.DataSource = LibSections.GetSections();
GridView1.DataBind();
}

//protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
//{
// if (e.CommandName == "Delete")
// {
// long Id = Convert.ToInt64(e.CommandArgument);
// LibSection.Delete(Id);
// //DeleteRecordByID(Id);

// }
//}

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int rowIndex = e.RowIndex;
long Id = Convert.ToInt64(GridView1.DataKeys[e.RowIndex].Value);
//GridView1.DeleteRow(Id); OR Even This one
DeleteRecordByID(Id);
}
}
Subject: Applying confirmation for delete
Name: Prahsant Chalise
Date: 9/13/2007 4:08:09 AM
Comment:
Instead of applying <..onrowdatabount="define yourself".. >and further putting the Javascript; it will be more easiear if we put these following

CommandName="DeleteRow" runat="server">Delete


This finally removes coding of Rowdatabound

Subject: misspell
Name: saber
Date: 9/26/2007 3:11:33 AM
Comment:
Hello,
there is a misspell in the article:
"Using the ClientOnClick attribute"
should be:
"Using the OnClientClick attribute"
Subject: row command event
Name: manash
Date: 5/21/2008 2:04:27 AM
Comment:
realy very helpfull. Thanks A Lot!!!
Win a free book
You can win yourself ASP.NET AJAX in ACTION
Read details







Join WebHost4Life.com







Copyright GridViewGuy 2007-2008