Prevent Duplicate record insert in database if record exists in ASP.Net

Last Reply on Oct 04, 2013 06:56 AM By kalpesh

Posted on Oct 04, 2013 12:27 AM

I have create one registration form in that I want can not allow the dulicate name,I have write the method for check the name already exists or not,Suppose I have entered name Atul then save,again entered atul or space atul it will accepted, I want to check case sencetive can not be allow.please give me the solution.

You are viewing reply posted by: kalpesh on Oct 04, 2013 06:56 AM.
Posted on Oct 04, 2013 06:56 AM

Kindly check an Below Example for your referance

 In .aspx

<form id="form1" runat="server">
        <asp:Label ID="lblUserName" runat="server" Text="Name"></asp:Label>
        &nbsp;&nbsp;&nbsp; : &nbsp; 
        <asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
        <br />
        <asp:Label ID="lblLastName" runat="server" Text="LastName"></asp:Label>
        &nbsp;&nbsp;&nbsp; : &nbsp; 
        <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
        <br />
        <asp:Button ID="submit" runat="server" Text="Register" 
            onclick="submit_Click"  />
        <br />
        <asp:Label ID="lblerror" runat="server" ></asp:Label>

 // In .cs file 

    //On Submit Button Click Ii call UserExist Method If it exist then Show Message that user is exist 
    //Else if Return False then Insert User Registration Details
    protected void submit_Click(object sender, EventArgs e)
        bool UserExist;
        UserExist = this.UserExit();

        if (UserExist == false)
            /*Here you Write Code To Insert User details*/
            /*Here you Write Code To Display Message That user Already Exist*/

    // Created Method for check User By Name if it Exist or Not which return Boolen value
    // If it Exist it Return True 
    // If not Exist then it Return False
    private bool UserExit()
        string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        SqlConnection con = new SqlConnection(strConnString);

        SqlCommand cmd = new SqlCommand("Select * From Personaldetails Where Name =@Name ");
        cmd.Parameters.AddWithValue("@Name", txtUsername.Text.Trim());

        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;

        SqlDataReader rdr;
        rdr = cmd.ExecuteReader();
        if (rdr.HasRows)
            return true;
            return false;