Click here to Skip to main content
15,888,155 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a form in my windows form application that is for admin users so that they can add,edit and delete users. The problem i have is that admin can insert a new user which has the same username as another user which results in both users having duplicate usernames when logging into the system.

how can i prevent admin from inserting an already taken username when creating new accounts in the database.


C#
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|Data.mdf;Integrated Security=True");
                con.Open();
                SqlDataAdapter sda = new SqlDataAdapter("INSERT INTO Login (FirstName,Role,Username,Password,Surname) VALUES ('" + txtfirstname2.Text + "','" + rolecombo.Text + "','" + txtusername2.Text + "','" + txtpassword2.Text + "','" + txtsurname.Text + "')", con);
                sda.SelectCommand.ExecuteNonQuery();
                con.Close();
                MessageBox.Show("SAVED SUCCESSFULLY !!!!!");


What I have tried:

I have looked across many articles which suggested adding an identity to usernames to make them unique, since i already have an ID column in the table which has an identity, i can not use the solution so therefore I need a simpler solution such as the system throwing a messagebox if username is duplicate but i'm not sure how to do that.
Posted
Updated 9-Mar-16 11:28am

1 solution

You can define columns as unique without them being an identity column. Nonetheless I would check whether a username already exists and not wait for the database code to throw an exception.

Apart from that: DON'T EVER use string-concatenation to build SQL-statements. Your code becomes susceptible to SQL-injection! Use SQL-Parameters instead.
 
Share this answer
 
v2
Comments
Member 12381237 9-Mar-16 18:01pm    
How would i check to see if username already exists in my code?
Sascha Lefèvre 9-Mar-16 18:12pm    
With a select query :) e.g.:
SELECT 1 FROM [Users] WHERE [UserName] = @username;
(The last bit is a name of an SQL-parameter, which you should use.)
Member 12381237 9-Mar-16 18:14pm    
Thanks and yes i will use SQL - parameters in the future, just making a really basic application at the moment.
Sascha Lefèvre 9-Mar-16 18:19pm    
You're welcome! :)

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