Tuesday, April 10, 2012

Launch a javascript alert or confirmation from a button located within a GridView control

I recently ran into a situation in which the business owner wanted to add a javascript popup that would confirm that the user did indeed wish to delete the selected row from a given GridView.  Originally, I was using a standard ButtonField control to display the delete button in the GridView which I've presented as follows:

<asp:ButtonField CommandName="DeleteRecord" ControlStyle-Height="23px" ControlStyle-Width="75px" ControlStyle-CssClass="GridView_Delete_Button" />

but, decided to switch gears and use the following code instead to incorporate that javascript popup:

<asp:TemplateField>
      <ItemTemplate>
           <asp:Button ID="btnDeleteParentCode" runat="server" ControlStyle-Height="23px" ControlStyle-Width="75px"
                 ControlStyle-CssClass="GridView_Delete_Button" CommandName="DeleteRecord" CommandArgument="<%# Container.DataItemIndex %>"
                 OnClientClick="return confirm('Are you certain you wish to delete the selected record');" />
     </ItemTemplate>
</asp:TemplateField>

The good news is that this new solution will work exactly like the previous ButtonField control with regards to your GridView_RowCommand event so you won't have to change any of your code in that event.  This is due to the additional CommandArgument attribute that you see in the Button control that will pass the selected row index in similar fashion to what takes place automatically with the previous ButtonField control.

In the event that you'd prefer to use a javascript alert instead of a confirmation, here's some sample code for that as well...

<asp:TemplateField>
     <ItemTemplate>
          <asp:Button ID="btnMove" runat="server" ControlStyle-Height="23px" ControlStyle-Width="75px"
               ControlStyle-CssClass="GridView_Move_Button" CommandName="Move" CommandArgument="<%# Container.DataItemIndex %>"
               OnClientClick="return alert('The record you've selected has been moved to a new location');" />
     </ItemTemplate>
</asp:TemplateField>

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.