Click here to Skip to main content
15,894,343 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a winform 'register user', now before the form is submitted, i want to check the database if the username entered by the user is alredy in the database. if the username exist a messagebox should be displayed else the form is submitted.pls code wil b of great help tanx in advance
Posted

You can use SQL EXIST to check whether the UserID exists in your table or not.
Use this command to check if the user is already exists:
SQL
DECLARE UserID VARCHAR(20) = 'test@test.com'
IF EXIST(SELECT * FROM tbUser WHERE UserID = @UserID)
BEGIN
    Print 'User Already Exist'
END
ELSE
BEGIN
    INSERT INTO tbUser VALUES(@UserID, 'Other Column Value')
END



--Amit
 
Share this answer
 
Comments
ridoy 7-Sep-12 3:48am    
correct..+5
_Amy 7-Sep-12 4:37am    
Thank you ridoy. :)
Ese ochuko 9-Sep-12 3:44am    
Hi thanks for your response, am using sqlserver an i am linkin my winform to it,this code u gave me where am i going to place it. Can you help me with a step by step example so i can undastand it more clearly.thaaaaaannnnnkkkss
Create a SP and return a result in dataset , then check if dataset has rows , if row count =1 then user exists

Something like this

C#
Dataset dscheckuser=checkexists (txtusername.Text.Trim)
if(dscheckuser.table[0].rows.count > 0)
{
   // user exists 
}else
{
   // insert new user
}
 
Share this answer
 
v2
Comments
Ese ochuko 10-Sep-12 1:22am    
Hithanks for your reply.you knw i have not done this bfore. in the code you gave to me, visual studio is not recognising the 'checkexist' is it a key word or what?. Can you please xplain the code with comment.thank you very much
One way to do it would be write a stored procedure that takes user ID as parameter and checks to see if its in the database.
Here is a sample
SQL
CREATE PROCEDURE usp_CheckUserExists
@UserID INT

AS
BEGIN

DECLARE @UserExists BIT

IF EXISTS(SELECT 1 FROM [Your User Table] WHERE UserID = @UserID)
BEGIN
    SET @UserExists = 1
END
ELSE
BEGIN
    SET @UserExists = 0
END

SELECT @UserExists AS UserExists

END


The SP returns true or false based on whether the user ID exists or not. You can take this result in your application to check if the user ID exists before creating the user.
 
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