An easy way to bind 'DELETE confirmation message' to .NET controls



 You always come accross a confirmation message "Are you sure you want to delete this item ? " while deleting an item. In web application basically  we attach a javascript function with the OnClientClick event of the server control to ask user confirmation before delete the item.

     So this is not a big problem if we have a single server control like Button control to call the javascript function through the OnClientClick event like:

 function ConfirmDelete()
 {
          if(confirm("Are you sure you want to delete this item ?"))
         {
              return true;
         }
         else
         {
              return false;
          }       
 }

    But in case of GridView control if we need a confirmation message before deleting any row items from the grid then we have to bind the javascript function for each row's OnClientClick event of the grid control. This is a bit complex process. So we can have the other way to do this and can be done without binding the javascript function to each row's OnClientClick event of the grid.
Solutions:
 
1. Here we have a function The 'ConfirmDelete()' which is executed each time a click event occurs on the page.
2. Then we use a logic that to find which element was clicked on i.s we append a word 'DELETE' to the ID of the control.
3.And finally check if the clicked element having ID is 'DELETED' , then the javascript function will be execute to ask the user about his/her confirmation.
 
JavaScript code:
 
 function ConfirmDelete(e)
 {   
         var targ;
       
         if (!e)
        {  
            var e = window.event;
         }
         targ = (e.target) ? e.target : e.srcElement;
       
         if (targ.nodeType == 3)
         {
              targ = targ.parentNode;
         }
       
        if (targ.id.toLowerCase().indexOf("delete") >= 0)
        {       
              return confirm("Do you want to delete this item?");
         }
         routeEvent(e);
     } 
 document.onclick = ConfirmDelete;
 
aspx  code:

 <asp:GridView RunAt="server" ID="gvTest" DataSourceID="SqlDataSource1">
            <Columns>      
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton runat="server"
                               ID="DeleteMe" Text="Delete" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

0 comments: