Pages

Search

Wednesday, February 11, 2009

Confirmation before deleting a record in .NET.

Delete buttons in user interface are very danger to perform delete action when clicked with out re confirming from user. This is because user may accidentally or with out knowledge may click on the delete button, which may lead to loss of imperative information.
We can handle this with the help of “confirm” box through JavaScript.
When an asp control like button or link button is clicked, obviously the page gets post backed which then calls the function that should be through onclick event of the button.

Asp control like button or link button have a property member saying “Attributes”. This property helps to add attributes for that component that are rendered on client side browser when the page is loaded.
There fore we can add “onclick” as an attribute and handle a kind of confirmation box before deleting a record.
Example:-
My page is as below,



Code behind page
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Delete : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnDelete_Click(object sender, EventArgs e)
{
//Lines of code for deleting a record
lblMessage.Text = "Deleted succesfully";
}
}



We can find that the code behind page “btnDelete_Click” function is called upon clicking the “Delete” button. After the record is deleted we display message as successfully deleted in the label.
In this case as soon user clicks on the delete button (knowingly or unknowingly), the page gets post backed and does the delete functionality written in the “btnDelete_Click” function written in code behind page.



Now
My code behind page
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Delete : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Adding on click javascript attribute to handle user confirmation before
//deleting the record
btnDelete.Attributes.Add("onclick", "return confirm('Are you sure to delete?');");
}
protected void btnDelete_Click(object sender, EventArgs e)
{
//Lines of code for deleting a record
lblMessage.Text = "Deleted succesfully";
}
}



If I run the page now, after clicking on “delete” button




If I click ok then



If I click on “cancel” button, then nothing happens or page does not get post backed.


No comments:

Post a Comment