Vinz' Blog

"Code, Beer and Music" ~ my way of being a programmer!
posts - 124, comments - 367, trackbacks - 0

My Links

News

Archives

Image Galleries

Display Confirmation Message on GridView Deleting

This demo describes the different approach to display a confirmation message when deleting a row in GridView and pass the id of the item to the confirmation message. Confirmation means a user is asked first if he/she wanted to delete a record by choosing an option (OK and CANCEL).
In this demo, we use the JavaScript confirm function for displaying the confirmation message. Now let’s create our JavaScript confirm function. To do this switch to ASPX source and add the following code block within the <head> tag like:
<head runat="server">
    <title>GridView Data Manipulation</title>
    <script type="text/javascript" language="javascript">
        function ConfirmOnDelete(item)
        {
          if (confirm("Are you sure to delete: " + item + "?")==true)
            return true;
          else
            return false;
        }
    </script>
</head>
 
Since we are done setting up our JavaScript function, we can simply call that function in our codes when deleting a row in GridView. Here are the following approaches below:
 
Option A: Using the ShowDeleteButton CommandField
The ShowDeleteButton CommandField is a built-in command in GridView to preform delete. I used this option in my previous example about “GridView Edit, Insert,Update and Delete” for deleting the data . Here’s a way to attach our JavaScript confirm in our codes when using ShowDeleteButton.
Assuming that we have this GridView Column mark up:
<Columns>
    <asp:BoundField DataField="CustomerID" HeaderText="ID" ReadOnly="true" />
    <asp:BoundField DataField="CompanyName" HeaderText="Company"/>
    <asp:BoundField DataField="ContactName" HeaderText="Name"/>
    <asp:BoundField DataField="ContactTitle" HeaderText="Title" />
    <asp:BoundField DataField="Address" HeaderText="Address"/>
    <asp:BoundField DataField="Country" HeaderText="Country"/>
    <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
</Columns>
 
At RowDataBound event, we can add an attribute to the control for calling the JavaScript confirm function when deleting. See below
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowState != DataControlRowState.Edit) // check for RowState
   {
     if (e.Row.RowType == DataControlRowType.DataRow) //check for RowType
     {
       string id = e.Row.Cells[0].Text; // Get the id to be deleted
       LinkButton lb = (LinkButton)e.Row.Cells[6].Controls[2]; //cast the ShowDeleteButton link to linkbutton
       if (lb != null)
       {
          lb.Attributes.Add("onclick", "return ConfirmOnDelete('" + id + "');"); //attach the JavaScript function with the ID as the paramter
       }      
      }
  }
}
 
As you can see from the above code blocks, we attached the JavaScript function in the LinkButton by adding an attributes to the control. But before that we need to check the RowState of the GridView first to ensure that the GridView is not on Edit Mode. If you failed to check for its RowState then you will get unexpected outcome. Second we checked for the RowType to ensure that we are on the right track for finding the control in the GridView. Please note that GridView is composed of six RowTypes namely (DataRow, EmptyDataRow, Header, Footer, Separator and Pager), so when accessing a control at RowDataBound event of GridView you must always check for its RowType.
We used the method Controls [index] because the CommandField columns doesn’t have an ID for us to use FindControl method. In addition we cannot even set an ID to a CommandField column.
As you can see, we passed the value of 6 in the cells index. This means that the ShowDeleteButton link is located at the 7th column of the GridView (see GridView mark up above), by default cells index starts at 0.
We passed the value of 2 in the Controls index in order to get reference to the ShowDeleteButton link. Based from the GridView mark up above we can see the controls sequence at the 7th columns below.
e.Row.Cells[6].Controls[0] – index 0 reference to ShowEditButton link
e.Row.Cells[6].Controls[1] – index 1 reference to a Literal control that separates between the ShowEditButton and ShowDeleteButton.
e.Row.Cells[6].Controls[2] – index 2 reference to ShowDeleteButton link
e.Row.Cells[6].Controls[3] – you will get null reference expection when passing index 3 and up J
Option B: Using TemplateField with LinkButton
Assuming that we have this GridView Column mark up below
<Columns>
 <asp:BoundField DataField="CustomerID" HeaderText="ID" ReadOnly="true" />
 <asp:BoundField DataField="CompanyName" HeaderText="Company"/>
 <asp:BoundField DataField="ContactName" HeaderText="Name"/>
 <asp:BoundField DataField="ContactTitle" HeaderText="Title" />
 <asp:BoundField DataField="Address" HeaderText="Address"/>
 <asp:BoundField DataField="Country" HeaderText="Country"/>
 <asp:TemplateField>
      <ItemTemplate>
      <asp:LinkButton ID="LinkDelete" runat="server">Delete</asp:LinkButton>
      </ItemTemplate>
 </asp:TemplateField>
</Columns>
 
The Declarative Approach:
When using TemplateField, we can directly use the OnClientClick event the ASPNET LinkButton server control and call the JavaScript confirm function at the mark up like below:
<ItemTemplate>
 <asp:LinkButton ID=" LinkDelete " runat="server" OnClick="LinkDelete _Click" OnClientClick="return ConfirmOnDelete('');">Delete</asp:LinkButton>
</ItemTemplate>
 
Note that using the above approach we cannot directly pass the value of the id to be deleted as a paramter in the confirm function that’s why we passed an empty value.
The Code Behind Approach:
The code behind approach is almost the same as what we did using the RowDataBound event for accessing the ShowDeleteButton. See below
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
 if (e.Row.RowState != DataControlRowState.Edit) // check for RowState
 {
    if (e.Row.RowType == DataControlRowType.DataRow) //check for RowType
    {
      string id = e.Row.Cells[0].Text; // Get the id to be deleted
      LinkButton lb = (LinkButton)e.Row.Cells[6].FindControl("LinkDelete"); //access the LinkButton from the TemplateField using FindControl method
      if (lb != null)
      {
        lb.Attributes.Add("onclick", "return ConfirmOnDelete('" + id + "');"); //attach the JavaScript function
      }
     }
 }
}
 
The only main difference from the above approach is that we are using FindControl method for referencing the control from the TemplateField based on the LinkButton’s ID.
Here’s the screen shot below for displaying a Confirmation when deleting.
 
That’s simple!

Print | posted on Sunday, February 22, 2009 1:52 AM |

Feedback

Gravatar

# re: Display Confirmation Message on GridView Deleting

I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.

Miriam

http://www.craigslistguide.info
2/23/2009 8:38 PM | Miriam
Gravatar

# re: Display Confirmation Message on GridView Deleting

Hi vinz

Really this is the best blog i ever read so long...
You are doing the great job, Keep on doing this this will help lot of developers..

Your presentation is good, i felt happy after seeing your bolg
REALLY NICE BOLG

3/2/2009 5:44 PM | praveen khade
Gravatar

# re: Display Confirmation Message on GridView Deleting

Hi vinz
can u place the code for delete a record that i confirmed
from Confirmation Message on GridView Deleting
3/30/2009 1:42 AM | adil
Gravatar

# re: Display Confirmation Message on GridView Deleting

Hi Adil,

Actually you can but if you place the codes for attaching the Button attributes at GridView_Deleting then the pop up will not comes up on first attempt.. Probably it would pops the confirmation on the second click of the delete button..
4/1/2009 9:51 PM | Vinz
Gravatar

# re: Display Confirmation Message on GridView Deleting

Hi, I guess one criteria is missing for RowDataBound because it is showing 'Confirm Delete' when you click on 'Cancel' Edit for Alternate rows. The reason being the row.RowState is 'Alternate | Edit' and not just DataControlRowState.Edit. Please verify.
4/5/2009 5:40 PM | Ketrishia
Gravatar

# re: Display Confirmation Message on GridView Deleting

hi Im new in aso.net
this post is really good and help me to understand d grid view editable mode
7/5/2009 10:36 PM | chanchal
Gravatar

# re: Display Confirmation Message on GridView Deleting

HI
i to new to asp.net
I know every thing about row.state by reading this post
7/22/2009 8:52 PM | subrahmanyam
Gravatar

# re: Display Confirmation Message on GridView Deleting

There is a error in the example. In order to get the link button to do the delete you need to add a attribute called CommandName with value 'delete'

Further the javascript function can be simplified as ahown below.

function ConfirmDelete()
{
return confirm("Are you sure to delete?");
}


<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton
ID="LinkDelete"
runat="server"
CommandName="delete"
OnClientClick="return ConfirmDelete();">Delete
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>


I want to add saying that this applies using VisualStudio 2008
8/28/2009 5:24 AM | Bart Burkhardt
Gravatar

# re: Display Confirmation Message on GridView Deleting

@Bart,

Setting CommandName for LinkButton is not necessary since we can also call the delete logic at Button_CLick event. BTW, what is the error you are getting?
8/30/2009 5:07 PM | Vinz
Gravatar

# re: Display Confirmation Message on GridView Deleting

great info!!!
i want to ask!
if i have a gridview just like yours but instead the delete button is not in the gridview, its outside of the gridview. and on the gridview itself, i have a checkbox in each row, to enable user to delete one or more record at the same time(by checking the the checkbox in the gridview) now my question is?

how to display the confirmation box only when one or more checkbox is checked furthermore if i press cancel on the confirmation box i dont want it to postback!!

and this one is optional, how do you pass the id value into the confirmation box? (if using the above method)
9/22/2009 3:49 PM | LoxZ
Gravatar

# re: Display Confirmation Message on GridView Deleting

@LoxZ

Check this example:

http://geekswithblogs.net/dotNETvinz/archive/2009/02/22/gridview-multiple-delete-with-checkbox-and-confirm.aspx
9/22/2009 4:58 PM | Vinz
Gravatar

# re: Display Confirmation Message on GridView Deleting

nice work
10/30/2009 6:06 PM | chamara
Gravatar

# re: Display Confirmation Message on GridView Deleting

Hi! I am a learner and thanks for ur code.it works
11/17/2009 11:09 PM | vishal
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: