Saturday, April 9, 2016

Asp.net: How to avoid duplicate record insert on page refresh

In this tutorial I am going to explain how to avoid (prevent) duplicate record insert on page refresh in asp.net using C#, VB.net


Description:
After insert the record when we refresh the page, it will reinsert (duplicate) the record with same values. In this article I am going to explain the solution to insert duplicate entries.

Implementation:

HTML Markup:
  <fieldset style="width:30%">
        <legend>Avoid Duplicate record Insert on page refresh</legend>
        <table>
            <tr><td>Movie name :</td><td>
                <asp:TextBox ID="txtname" runat="server"></asp:TextBox></td></tr>
            <tr><td>Genre :</td><td>
                <asp:TextBox ID="txtgenre" runat="server"></asp:TextBox></td></tr>
            <tr><td>Budget :</td><td>
                <asp:TextBox ID="txtbudget" runat="server"></asp:TextBox></td></tr>
            <tr><td></td><td></td></tr>
            <tr><td></td><td>
                <asp:Button ID="btninsert" runat="server" Text="Save"/></td></tr>
            <tr><td colspan="2">
                <asp:Label ID="lblmessage" runat="server"></asp:Label></td></tr>
        </table>
    </fieldset>

Import/add the namespace
C# code:
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

VB.net code:
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient

Solution 1: Check record already exist or not
We have to check the duplicate record before inserting the record. If the record with same value exists, it will not insert the record into database.

Create Store Procedure to check the record exist
Create PROCEDURE Sp_InsertMovie
(
@name varchar(50),
@genre varchar(50),
@budget int,
@outputmessage varchar(1000) out
)
AS
BEGIN
            SET NOCOUNT ON;
if not Exists (Select * from Tb_Movie where Name=@name and Genre=@genre and Budget=@budget)
Begin
Insert into Tb_Movie (Name,Genre,Budget) values(@name,@genre,@budget)
set @outputmessage = 'Record Insert Successfully'
END
else
begin
set @outputmessage = 'Record Already Exist'
end
End

On button click right the below given code:
C# code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
protected void btninsert_Click(object sender, EventArgs e)
    {
        try
        {
            SqlCommand cmd = new SqlCommand("Sp_InsertMovie", con);
            cmd.CommandType = CommandType.StoredProcedure;
            con.Open();
            cmd.Parameters.AddWithValue("@name", txtname.Text);
            cmd.Parameters.AddWithValue("@genre", txtgenre.Text);
            cmd.Parameters.AddWithValue("@budget", txtbudget.Text);
            cmd.Parameters.Add("@outputmessage", SqlDbType.Char, 500);


            cmd.Parameters["@outputmessage"].Direction = ParameterDirection.Output;
            string message = (string)cmd.Parameters["@outputmessage"].Value;
            cmd.ExecuteNonQuery();
            con.Close();
            lblmessage.Text = message;
        }
        catch (Exception ex) { }
    }

VB.net Code:
  Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("con").ToString())
    Protected Sub btninsert_Click(sender As Object, e As EventArgs) Handles btninsert.Click
        Try
            Dim cmd As New SqlCommand("Sp_InsertMovie", con)
            cmd.CommandType = CommandType.StoredProcedure
            con.Open()
            cmd.Parameters.AddWithValue("@name", txtname.Text)
            cmd.Parameters.AddWithValue("@genre", txtgenre.Text)
            cmd.Parameters.AddWithValue("@budget", txtbudget.Text)
            cmd.Parameters.Add("@outputmessage", SqlDbType.[Char], 500)
            cmd.Parameters("@outputmessage").Direction = ParameterDirection.Output
            Dim message As String = DirectCast(cmd.Parameters("@outputmessage").Value, String)
            cmd.ExecuteNonQuery()
            con.Close()
            lblmessage.Text = message
        Catch ex As Exception
        End Try
    End Sub



Create store Procedure:
Create PROCEDURE Sp_InsertMovie
(
@name varchar(50),
@genre varchar(50),
@budget int
)
AS
BEGIN
            SET NOCOUNT ON;
Insert into Tb_Movie (Name,Genre,Budget) values(@name,@genre,@budget)
END

Solution 2: Redirect to same page
After insert the record redirect the user to same page.

C# code:
protected void btninsert_Click(object sender, EventArgs e)
    {
        try
        {
            SqlCommand cmd = new SqlCommand("Sp_InsertMovie", con);
            cmd.CommandType = CommandType.StoredProcedure;
            con.Open();
            cmd.Parameters.AddWithValue("@name", txtname.Text);
            cmd.Parameters.AddWithValue("@genre", txtgenre.Text);
            cmd.Parameters.AddWithValue("@budget", txtbudget.Text);          
            cmd.ExecuteNonQuery();
            con.Close();
            Response.Write("<script>alert('Record Insert Successfully');window.location='Default.aspx';</script>");
          //  Response.Redirect(Request.Url.AbsoluteUri);
        }
        catch (Exception ex) { }
    }

Vb.net code:
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("con").ToString())
    Protected Sub btninsert_Click(sender As Object, e As EventArgs) Handles btninsert.Click
      Try
            Dim cmd As New SqlCommand("Sp_InsertMovie", con)
            cmd.CommandType = CommandType.StoredProcedure
            con.Open()
            cmd.Parameters.AddWithValue("@name", txtname.Text)
            cmd.Parameters.AddWithValue("@genre", txtgenre.Text)
            cmd.Parameters.AddWithValue("@budget", txtbudget.Text)
            cmd.ExecuteNonQuery()
            con.Close()
            '  Response.Redirect(Request.Url.AbsoluteUri);
            Response.Write("<script>alert('Record Insert Successfully');window.location='Default.aspx';</script>")
        Catch ex As Exception
        End Try
    End Sub

Solution 3: Redirect to another page
After insert the record redirect the user to another (success) page.

C# code:
protected void btninsert_Click(object sender, EventArgs e)
    {
        try
        {
            SqlCommand cmd = new SqlCommand("Sp_InsertMovie", con);
            cmd.CommandType = CommandType.StoredProcedure;
            con.Open();
            cmd.Parameters.AddWithValue("@name", txtname.Text);
            cmd.Parameters.AddWithValue("@genre", txtgenre.Text);
            cmd.Parameters.AddWithValue("@budget", txtbudget.Text);          
            cmd.ExecuteNonQuery();
            con.Close();
            Response.Write("<script>alert('Record Insert Successfully');window.location='frmsuccess.aspx';</script>");
        }
        catch (Exception ex) { }
    }

Vb.net code:
Protected Sub btninsert_Click(sender As Object, e As EventArgs) Handles btninsert.Click
      Try
            Dim cmd As New SqlCommand("Sp_InsertMovie", con)
            cmd.CommandType = CommandType.StoredProcedure
            con.Open()
            cmd.Parameters.AddWithValue("@name", txtname.Text)
            cmd.Parameters.AddWithValue("@genre", txtgenre.Text)
            cmd.Parameters.AddWithValue("@budget", txtbudget.Text)
            cmd.ExecuteNonQuery()
            con.Close()
            Response.Write("<script>alert('Record Insert Successfully');window.location='frmsuccess.aspx';</script>")
        Catch ex As Exception
        End Try
    End Sub  

No comments:

Post a Comment