Click here to Skip to main content
15,890,741 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have a details view and a button, and when I click on the button, I want to check if the username is already in the database or not.

I tried the below code and I tested it with button and it worked, but know I want to assign it to the insert command of the detailsview. I tried to put it in DetailsView1_ItemInserting but in case of if statement it gives me the yellow error page with PK duplication, but in case of else statement is works fine. Any Help??

What I have tried:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            string query = "select Username from [Login] where Username = '" + ((TextBox)DetailsView1.FindControl("TextBox1")).Text + "'";
            SqlCommand cmd = new SqlCommand(query, con);
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();

            dr.Read();
            if (dr.HasRows == true)
            {

                //error message here

            }
            else
            {
                //success message here
            }

            con.Close();
Posted
Updated 27-Apr-17 13:06pm

1 solution

Apart from the "SQL Injection Attack" (Seriously, Google it, you risk the destruction of your database!) you're opening yourself up to, it's a bad idea to use a SELECT to see if something is there first and then INSERT. What would happen if two people tried to register the exact same username? One of them is going to succeed and the other is going to fail even though your SELECT said it was available. The order of SQL statements from each user would be:
User1                 User2
SELECT (available!)
                      SELECT (available!)
INSERT (succeeds!)
                      INSERT (fails - duplicate)

A better way to do it would be to just try the INSERT and catch the exception if it's a duplicate. If there's no exception, you know it worked. If there was an exception, it was a duplicate.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900