How to prevent duplicate record/data entry on page refresh in asp.net

Introduction: In this article i am going to explain How to prevent/avoid/stop duplicate record entry insertion when page is refreshed by clicking on browser's refresh button in asp.net using C# and VB.Net languages.In previous articles i explained How to Disable browser autocomplete feature in TextBox and Retain password value in TextBox after postback and Get browser name,version,type, operating system and Get Title,Description and Keywords Meta tags from URL and Count and display remaining characters in the multiline textbox and Get current page URL/Address  and Create log file to record errors and exceptions.

Prevent duplicate record entry in database on refreshing browser

Description: While developing input forms in Asp.Net many of the developers face a very common issue i.e. insertion of same/duplicate data on refreshing browser by clicking on refresh button or hitting F5. Browser display the above popup message on refreshing page.

Reason: Whenever browser is refreshed it will resend the last request to the website, so when we click on refresh after submitting the record it will insert the new entry of duplicate data in the database.

Solution: we can handle this duplicate insertion of data on browser refresh problem using the three techniques mentioned below: 
  1. Redirect to another page after successfully submitting the form.
  2. Redirect to same page after successfully submitting the form.
  3. Check for already existing duplicate data before submitting record.

 Implementation: Let's discuss 3 these techniques using suitable example. 
  • First of all In the Sql server database create the database e.g. "EmpDb" and in this create a table "Tb_Emp" with the Columns and their data types as shown in image below:

Column Name
Data Type
EmpId
Int(Primary Key. So set Is Identity=True
EmpName
varchar(50)
Age
Int
Salary
decimal(18, 0)
Address
varchar(500)
  
  • In the web.config file create the connection string as:
 <connectionStrings>
    <add name="conStr" connectionString="Data Source=LALIT;Initial Catalog=EmpDb;Integrated Security=True;Pooling=False"/>
  </connectionStrings>
  <system.web>

Note: Replace the Data Source and Initial Catalog as per your application. 
  • In the <Form> tag of design page (.aspx) design the input form as:
Avoid duplicate record entry in database on refreshing browser

HTML Source code

<div>
   <fieldset style="width:300px;">
   <legend>Prevent Duplicate entry on browser refresh</legend>  
    <table>
    <tr>
    <td>Name: </td>
    <td>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
    </tr>
    <tr>
    <td>Age: </td>
    <td>
        <asp:TextBox ID="txtAge" runat="server"></asp:TextBox></td>
    </tr>
    <tr>
    <td>Salary</td>
    <td>
        <asp:TextBox ID="txtSalary" runat="server"></asp:TextBox></td>
    </tr>
    <tr>
    <td>Address</td>
    <td>
        <asp:TextBox ID="txtAddress" runat="server" TextMode="MultiLine"></asp:TextBox></td>
    </tr>
    <tr>
    <td></td>
    <td>
        <asp:Button ID="btnSubmit" runat="server" Text="Submit"
            onclick="btnSubmit_Click" />
        </td>
    </tr>
    </table>
   </fieldset>
    </div> 

Redirect to another page after successfully submitting the form.

Suppose you want to show success page e.g. "Successpage.aspx" after record submission then use the code mentioned below

C#.Net Code

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
        SqlCommand cmd = new SqlCommand("Insert into Tb_Emp (EmpName,Age,Salary,[Address]) values (@EmpName,@Age,@Salary,@Address)", con);
        cmd.Parameters.AddWithValue("@EmpName", txtName.Text.Trim());
        cmd.Parameters.AddWithValue("@Age", txtAge.Text.Trim());
        cmd.Parameters.AddWithValue("@Salary", txtSalary.Text.Trim());
        cmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim());

        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Record saved successfully.');window.location='SuccessPage.aspx';", true);
        }
        catch (Exception ex)
        {
            Response.Write("Oops !! Following error occured: " + ex.Message.ToString());
        }
        finally
        {
            con.Close();
            cmd.Dispose();
        }
    }

VB.Net Code

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
        Dim cmd As New SqlCommand("Insert into Tb_Emp (EmpName,Age,Salary,[Address]) values (@EmpName,@Age,@Salary,@Address)", con)
        cmd.Parameters.AddWithValue("@EmpName", txtName.Text.Trim())
        cmd.Parameters.AddWithValue("@Age", txtAge.Text.Trim())
        cmd.Parameters.AddWithValue("@Salary", txtSalary.Text.Trim())
        cmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim())

        Try
            con.Open()
            cmd.ExecuteNonQuery()
            ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "popup", "alert('Record saved successfully.');window.location='SuccessPage.aspx';", True)
        Catch ex As Exception
            Response.Write("Oops !! Following error occured: " & ex.Message.ToString())
        Finally
            con.Close()
            cmd.Dispose()
        End Try
    End Sub


Redirect to same page after successfully submitting the form.

Suppose you have input form on the "default page" then redirect to same "default.aspx" after record submission as mentioned below

C#.Net Code

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
        SqlCommand cmd = new SqlCommand("Insert into Tb_Emp (EmpName,Age,Salary,[Address]) values (@EmpName,@Age,@Salary,@Address)", con);
        cmd.Parameters.AddWithValue("@EmpName", txtName.Text.Trim());
        cmd.Parameters.AddWithValue("@Age", txtAge.Text.Trim());
        cmd.Parameters.AddWithValue("@Salary", txtSalary.Text.Trim());
        cmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim());

        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Record saved successfully.');window.location='default.aspx';", true);
        }
        catch (Exception ex)
        {
            Response.Write("Oops !! Following error occured: " + ex.Message.ToString());
        }
        finally
        {
            con.Close();
            cmd.Dispose();
        }
    }

VB.Net Code

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
        Dim cmd As New SqlCommand("Insert into Tb_Emp (EmpName,Age,Salary,[Address]) values (@EmpName,@Age,@Salary,@Address)", con)
        cmd.Parameters.AddWithValue("@EmpName", txtName.Text.Trim())
        cmd.Parameters.AddWithValue("@Age", txtAge.Text.Trim())
        cmd.Parameters.AddWithValue("@Salary", txtSalary.Text.Trim())
        cmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim())

        Try
            con.Open()
            cmd.ExecuteNonQuery()
            ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "popup", "alert('Record saved successfully.');window.location='default.aspx';", True)
        Catch ex As Exception
            Response.Write("Oops !! Following error occured: " & ex.Message.ToString())
        Finally
            con.Close()
            cmd.Dispose()
        End Try
    End Sub


Check for already existing duplicate data before submitting record.

The logic is simple. We need to check for the same entry every time before inserting a new record. If the same record is not in the database then it insert the record in the database otherwise not. So we need to create the Stored procedure to perform this.

Note: On refreshing browser it will still show the "Confirm Form Submission" popup message but will not make duplicate entry.

CREATE PROCEDURE [dbo].[SaveEmpRecord_Sp]
                @EmpName     varchar(50),
                @Age                    int,
                @Salary                               decimal(18,0),
                @Address           varchar(500)
AS
BEGIN
                If not exists(select * from Tb_Emp where EmpName=@EmpName and Age=@Age and Salary=@Salary and [Address]=@Address)
                Begin
                                Insert into Tb_Emp (EmpName,Age,Salary,[Address]) values (@EmpName,@Age,@Salary,@Address)
                End
END


C#.Net Code

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
        SqlCommand cmd = new SqlCommand("SaveEmpRecord_Sp", con);
        cmd.Parameters.AddWithValue("@EmpName", txtName.Text.Trim());
        cmd.Parameters.AddWithValue("@Age", txtAge.Text.Trim());
        cmd.Parameters.AddWithValue("@Salary", txtSalary.Text.Trim());
        cmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim());
        cmd.CommandType = CommandType.StoredProcedure;
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Record saved successfully');", true);
        }
        catch (Exception ex)
        {
            Response.Write("Oops !! Following error occured: " + ex.Message.ToString());
        }
        finally
        {
            con.Close();
            cmd.Dispose();
        }
    }


VB.Net code

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
        Dim cmd As New SqlCommand("SaveEmpRecord_Sp", con)
        cmd.Parameters.AddWithValue("@EmpName", txtName.Text.Trim())
        cmd.Parameters.AddWithValue("@Age", txtAge.Text.Trim())
        cmd.Parameters.AddWithValue("@Salary", txtSalary.Text.Trim())
        cmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim())
        cmd.CommandType = CommandType.StoredProcedure
        Try
            con.Open()
            cmd.ExecuteNonQuery()
            ScriptManager.RegisterClientScriptBlock(Page, Page.[GetType](), Guid.NewGuid().ToString(), "alert('Record saved successfully');", True)
        Catch ex As Exception
            Response.Write("Oops !! Following error occured: " & ex.Message.ToString())
        Finally
            con.Close()
            cmd.Dispose()
        End Try
    End Sub

Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."
Previous
Next Post »

9 comments

Click here for comments
Unknown
admin
November 10, 2013 ×

Hello sir.
Dear sir i want to hide (.aspx) extension in asp.net. plz send code on my gmail id is =abhimanyu.it@gmail.com
Thanks
Abhimanyu

Reply
avatar
November 10, 2013 ×

Hi Abhimanyu..You can handle this through URL routing..i will create an article as per your requirement and publish soon..so keep reading and stay connected for more updates..:)

Reply
avatar
Unknown
admin
November 10, 2013 ×

i am waiting for your article..thanks u sir...

Reply
avatar
SVD
admin
August 13, 2014 ×

Great article. Thanks sir.
Sinu

Reply
avatar
August 13, 2014 ×

your welcome Sinu..keep reading for more useful updates

Reply
avatar
October 04, 2015 ×

Thanks for your valuable feedback..

Reply
avatar
November 05, 2015 ×

This article is very useful Thank you

Reply
avatar
November 20, 2015 ×

Thanks sheebu for your valuable comment..Stay connected and keep reading for more useful updates.

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..