c# - Check if Username exists in Database -


i trying code register application form. in code below want check if username exists before save data in database. problem here code doesn't go "else" statement. miss something? kindly help

public void usernamecheck() {           string connetionstring = null;         sqlconnection con;         connetionstring = "data source=mcoeelimenem\\sqlexpress;initial catalog=database;integrated security=true";         con = new sqlconnection(connetionstring);          sqlcommand cmd = new sqlcommand("select * register username= @username", con);         cmd.parameters.addwithvalue("@username", this.textbox1.text);         con.open();         sqldatareader dr = cmd.executereader();         while (dr.read())         {             if (dr.hasrows == true)             {                 messagebox.show("username = " + dr[1].tostring() + " exist");                 break;               }             else             {                 cmd.commandtext = "insert register(username,password,fullname,mobileno,emailid) values( @username, @password, @fullname, @mobileno, @emailid)";                 cmd.parameters.addwithvalue("@username", textbox1.text);                 cmd.parameters.addwithvalue("@password", textbox2.text);                 cmd.parameters.addwithvalue("@fullname", textbox3.text);                 cmd.parameters.addwithvalue("@mobileno", textbox4.text);                 cmd.parameters.addwithvalue("@emailid", textbox5.text);                  cmd.executenonquery();                 messagebox.show("data inserted succesfully");                 con.close();                 this.hide();                 login lg = new login();                 lg.show();              }         } } 

the query not return rows (therefore read() statement fail) user exists.

try (untested):

sqlcommand cmd = new sqlcommand("select count(*) register username= @username", con); cmd.parameters.addwithvalue("@username", this.textbox1.text); con.open(); var result = cmd.executescalar(); if (result != null) {     messagebox.show(string.format("username {0} exist", this.textbox1.text)); } else {     ... 

Comments

Popular posts from this blog

C# random value from dictionary and tuple -

cgi - How do I interpret URLs without extension as files rather than missing directories in nginx? -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -