CodeSnip: Confirming Row Deletion in a GridView
page 1 of 1
Published: 14 Mar 2006
Unedited - Community Contributed
Abstract
In this article, Sushila demonstrates how to display a confirmation dialog box before performing a row deletion in a GridView.
by Sushila Bowalekar Patel
Feedback
Average Rating: 
Views (Total / Last 10 Days): 66385/ 34

Row deletion in a GridView by default does not provide confirmation before deleting.  Using a client-side verification message can prevent accidental deletions.  In this example, we will see how to utilize client-side script to confirm deletions when using a GridView control.

In ASP.NET 2.0, the Button, LinkButton, and ImageButton controls have an OnClientClick property.  We can use this property to specify the client-side JavaScript which will get executed when the button is clicked.  The CommandField property of the GridView control unfortunately does not have an OnClientClick property, but adding a button to the GridView can do the trick for us.

In this example, we will see how to use ASP.NET 2.0's OnClientClick property for the Button control with the GridView control to show a confirmation message before the user deletes the row.

Set Up the GridView

We will the use the GridView's TemplateField, containing an ItemTemplate, which in turn contains a Button control.  Such a button, with the CommandName set to Delete, will cause the GridView to delete the associated row when pressed.  Since our aim is to show a confirmation message before the deletion of the row, we will also make use of the button's OnClientClick property.

The button control's properties are assigned as follows:

·         OnClientClick to JavaScript confirm message

·         CommandName to Delete

The DataKeyNames property of the GridView control is used to specify the field or fields that represent the primary key of the data source.

Listing 1 – Display Data Using GridView Control

<asp:GridView ID="GridView1"runat="server" 
DataSourceID="SqlDataSource1" 
AutoGenerateColumns="False" 
DataKeyNames="EmployeeId">
<Columns>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
   <asp:Button ID="btnDelete" Text="Delete" runat="server"
OnClientClick="return confirm('Are you sureyou want to delete this record?');"
CommandName="Delete" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="EmployeeId" DataField="EmployeeId" />
<asp:BoundField HeaderText="FirstName" DataField="FirstName" />
<asp:BoundField HeaderText="LastName" DataField="LastName" />
</Columns>
</asp:GridView>

Next, we set the SqlDataSource DeleteCommand and its parameters.  EmployeeId is the primary key in the Employees table.  This key is used to delete the row.  The GridView needs to find which row has to be deleted, hence we used @original_EmployeeId and not @EmployeeId.  If we don't prefix this parameter with original_ then there is no way to find that row which has to be deleted.

Listing 2 – The SqlDataSource

<asp:SqlDataSource ID="SqlDataSource1"runat="server" 
ConnectionString="Server=localhost;Database=Northwind;userid=username;password=secret;" 
SelectCommand="Select * from Employees" 
DeleteCommand="Delete from Employees whereEmployeeId=@original_EmployeeId"
OnDeleted="SqlDataSource1_Deleted">
<DeleteParameters>
<asp:Parameter Type="Int32"Name="EmployeeId"></asp:Parameter>
</DeleteParameters>
</asp:SqlDataSource>
<asp:Label ID="lblShow"runat="server" ForeColor="DarkRed"></asp:Label>

To show a message to the end user after the row has been deleted we will use the Deleted event of the SqlDataSource control to do this task for us and also supply and error messages.

Listing 3 - The Deletion Code

Visual Basic .NET

Protected Sub SqlDataSource1_Deleted(ByVal sender AsObject, _
ByVal e AsSystem.Web.UI.WebControls.SqlDataSourceStatusEventArgs)
If e.Exception Is Nothing Then
  If e.AffectedRows = 1 Then
    lblShow.Text = "Record deletedsuccessfully."
  Else
    lblShow.Text = "An error occurred duringthe delete operation."
  End If
Else
  lblShow.Text = "An error occurred whileattempting to delete the row."
  e.ExceptionHandled = True
End If
End Sub

C#

protected void SqlDataSource1_Deleted(objectsender,
  SqlDataSourceStatusEventArgs e)
{
  if (e.Exception == null)
  {
    if (e.AffectedRows == 1)
    {
      lblShow.Text = "Record deletedsuccessfully.";
    }
    else
    {
      lblShow.Text = "An error occurredduring the delete operation.";
    }
  }
  else
  {
    lblShow.Text = "An error occurred whileattempting to delete the row.";
    e.ExceptionHandled = true;
  }
}

Screenshots

Figure 1 - GridView Before Deletion

Figure 2 - GridView After Deletion

Downloads

[Download Sample]

Conclusion

In this article you learned how to integrate a confirmation message box before deleting a row in a GridView, with a help of an example and relevant screenshots.



User Comments

Title: How will you display Confirmation box in C#?   
Name: Gokul
Date: 2007-05-31 1:10:07 AM
Comment:
Hai Sushila,
can you pls explain me How to display Confirmation box in C#?
I dont know that.
regards
Gokul
Title: Problem   
Name: Tan
Date: 2007-05-24 3:02:05 PM
Comment:
I set Datasource for GridView in code behind. I try exactly like this but it always jump into Griview_Delete either I choose OK or Cancel. I don't know why.
Thanks in advance.
Title: Good   
Name: Madhu
Date: 2007-05-18 7:31:25 AM
Comment:
the article helped me lot thank u very much
Title: Why SqlDatasource?   
Name: Mahernoz@gmail.com
Date: 2007-04-11 6:50:25 AM
Comment:
Hi Sushila,
I wonder why have you used SqlDataSource. As of now, no body uses this control for dataaccess. we use the ObjectDatasource or some people prefer just programmatic access.
Title: nice   
Name: Vijay
Date: 2007-01-18 2:51:42 AM
Comment:
hi Article "Acha Bohat Acha ahe" continue Enjoy the coding
Title: Dynamic fields.   
Name: Ali
Date: 2007-01-16 1:41:49 PM
Comment:
Hello how can i do if i am creating columns dynamically...?
Title: Beautiful article   
Name: Kamal
Date: 2006-11-22 6:56:01 AM
Comment:
Hi Sushila, its really a wonderful article, which help me a lot. Thanks. Keep it up.
Title: wont work with imagebuttom   
Name: Gemeni
Date: 2006-11-05 9:41:01 PM
Comment:
Would this work with an image button instead of just button?
Title: When using a commandfield   
Name: R
Date: 2006-09-06 5:59:23 AM
Comment:
There is a problem when using this technique in a CommandField whereby the page doesn't post back after the javascript confirm.

To overcome this, use this approach instead:

Sub gvRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
' code to locate button omitted
myButton.Attributes.Add("onclick", "if(!confirm('Are you sure you wish to delete?')) return false;")
End If
End Sub
Title: Excellence topic   
Name: kwan
Date: 2006-08-19 7:53:31 AM
Comment:
It's very helpful. .... Thank a lot
Title: THANK YOU!!!   
Name: New Programmer
Date: 2006-07-21 3:24:08 PM
Comment:
Thank you SO much!!! I've looked everywhere for this very thing!
Title: Useful and Informative   
Name: Jaya Krishna
Date: 2006-06-02 8:40:54 AM
Comment:
Thank you very much.. Just beginning ASP.Net and was struggling with C#. Clear explanation with example.
Title: Congratulation s   
Name: Bilal Hadiar [MVP]
Date: 2006-04-12 1:08:35 AM
Comment:
Hi Sushila:
As usual nice tips and tricks from you.

Good Luck,

Regards
Title: delete record from grid   
Name: manita
Date: 2006-04-04 1:34:44 AM
Comment:
hi sushila
i appreciste u r work. but can we do this coding by using function
Title: Good Article!!   
Name: Satya
Date: 2006-03-16 5:21:48 AM
Comment:
Hello Sushila,
I appreciate your work. It is very helpful for the novice programmers. Go Ahead ...

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2017 ASPAlliance.com  |  Page Processed at 2017-04-27 7:09:52 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search