database

How to avoid duplicate entry of a record in database when user hits refresh.

March 30, 2010

Problem

In case we are saving data in database on click of a button, and what happens if a user hits refresh??
The data will be saved twice in the database. How can we avoid this behavior??

Solution

Solution to avoid duplicate entry of a record in database

Here is the solution in case the website is being developed in asp.net version 1.1 + with C# as the scripting language. The below implementation is designed by keeping “Order of page lifecycle events” in mind. The event order is Page_Load => btnSubmit_Click => Page_PreRender. The following code can be implemented to avoid the problem.

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session[“RefrechCheck”] = DateTime.Now.ToString();
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
ViewState[“RefrechCheck”] = Session[“RefrechCheck”];
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid && Session[“RefrechCheck”].ToString() == ViewState[“RefrechCheck”].ToString())
{
Session[“RefrechCheck”] = DateTime.Now.ToString();
int result = SaveComment();
}
}

Happy coding.

Talk to Our Experts! Drop Your Contact Details
We will get back to you ASAP.
This site is protected by reCAPTCHA. Google's Privacy Policy and Terms of Service apply.
Recent Blog Posts
View More
Advantages of ASP.NET Development
Sep10

Advantages of ASP.NET Development

Advantages of ASP.NET Development ASP.Net is a powerful framework used for the development of dynamic web pages, website...
View More
View More
Benefits of Outsourcing Software Development to India
Jan20

Benefits of Outsourcing Software Development to India

Outsourcing Software Development: The most successful business strategy adopted by organizations worldwide today is certainly outsourcing their software...
View More