Tips, tricks, and frustrations from my years of building ASP.NET websites.

Saturday, April 5, 2008

Adding an 'Are You Sure' confirmation box to a GridView delete button.

When deleting a row in an ASP.NET GridView control, often times you would like to provide a confirmation dialog box with a simple message and the basic 'OK' and 'Cancel' buttons.

This isn't too hard to accomplish using:
1) Template column.
2) <asp:LinkButton> control and it's OnClientClick property.
3) A little JavaScript

<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton
ID="lbtnGridDelete"
runat="server"
CausesValidation="false"
CommandName="Delete"
OnClientClick='<%# Eval("Role","return confirm(\"Are you sure you want to delete role: {0}?\")") %>'
Text="Delete">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
The trick is to use the OnClientClick property of the LinkButton control. OnClientClick is the property you use to specifiy the JavaScript to execute when the delete button is clicked. In this case we use the Eval() function to formulate our JavaScript and print our message on the confirm() box. The value of the column named 'Role' will be placed in the message, for example: Are you sure you want to delete role: asdf?

The resulting confirm box will look like this:



When the users presses the delete button, the client side code will run to produce the JavaScript confirm() box. If the user presses the 'OK' button then the post back will occur and the delete processing will execute.

No comments:

About Me

I'm currently employed as a Senior Systems Programmer/Analyst and sometimes Project Manager at Texas Instruments Inc. in Plano TX.