ASP.NET Popup Dialog - Confirm Delete - Javascript

Update 4/1/2004: Given numerous requests for a DataGrid Example, I added a post with full source code showing 1 way to pull this off using a DataGrid: ASP.NET Popup Dialog - Confirm Delete - Javascript - DataGrid Example

In all good web applications, the user is asked to confirm whether he/she wants to delete something in case the delete button was pressed accidentally.

Although it seems like a pain to do, it is actually really easy if you find it acceptable to use javascript's “confirm” statement, which will popup a dialog box with a particular question with “ok” and “cancel” buttons. You have no control of the title of the popup, but in IE it says “Microsoft Internet Explorer“ and I believe it says “[Javascript Application]“ or similar in Firebird.





The javascript code for it is simple:


function confirm_delete()
{
  if (confirm("Are you sure you want to delete the custom search?")==true)
    return true;
  else
    return false;
}


Using code-behind, you can attach the javascript popup dialog to the button:


_myButton.Attributes.Add("onclick", "return confirm_delete();");


If the button is inside a repeater (in this case called Searches), for example, which most of mine our, you have to attach it as follows by handling the ItemCreated event:

override protected void OnInit(EventArgs e)
{
   base.OnInit(e);
   this.Load += new System.EventHandler(this.Page_Load);
   Searches.ItemCreated += new RepeaterItemEventHandler(this.Item_Created);
   Searches.ItemCommand += new RepeaterCommandEventHandler(this.DeleteSearch_Click);
}

private void Item_Created(Object Sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
      {
            ImageButton _myButton = (ImageButton)e.Item.FindControl("btnDelete");
            _myButton.Attributes.Add("onclick", "return confirm_delete();");
      }
}

private void DeleteSearch_Click(object sender, RepeaterCommandEventArgs e)
{
    int _id = Int32.Parse(e.CommandArgument.ToString());
    // Do Your Thing...
}


Inside your repeater, you add the button as such:


... ImageButton id=btnDelete ImageUrl="images/icon_delete.gif" runat="server" CommandArgument='<%# ((DataRowView)Container.DataItem)["ID"] %> ...

When you click on the delete button, the javascript popup dialog asks if you want to delete the search. If you choose “cancel“, your “DeleteSearch_Click” event is never fired. If you choose “ok”, the event is fired and you can delete the item.

Adds a bit of professionalism to your web applications without requiring a lot of effort.

posted on Tuesday, March 16, 2004 11:18 AM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices