How to check whether a username exists in our database or not?

Posted by Raja under C# category on | Points: 40 | Views : 4336
Generally we need to validate while designing a login page that entered username exists in our database or not, below is the codesnippet to do that.

string strSql = ""select AutoId from userslogin u where " + 
"u.UserName = @userName order by username";
SqlParameter[] prms = new SqlParameter[1];
prms[0] = new SqlParameter("@userName", SqlDbType.Varchar, 50);
prms[0].Value = userName; // passed as input to the method
object obj = base.ExecuteScalar(ConnStr, CommandType.Text, strSql); // here ConnStr is the connection string of your database.
if (obj != null)
return 0; // user exists in the database
// user doesn't exists in the database, proceed with inserting the record

Hope this helps

Comments or Responses

Posted by: Chvrsri on: 10/27/2010 Level:Silver | Status: [Member] [Moderator] [MVP] | Points: 10
Nice Post Raja !!! Useful...

Cheers !!!

Login to post response