Else doesn't work in reader using c# - c#

When I enter user name and password, it logs in successfully and also opens desired field but when I enter wrong name or password (not saved in DB) it shows nothing actually it should encounter "else" this is the code
private void signin_button_Click(object sender, EventArgs e)
{
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= D:/Student_Managment_System/SMS1.mdb";
OleDbConnection myConnection = new OleDbConnection(connectionString);
myConnection.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = myConnection;
string usrname = name_textBox.Text;
string passwd = pass_textBox.Text;
OleDbCommand cmd1 = new OleDbCommand("select * from Manager where Name='" + usrname + "' and Passwd='" + passwd + "'");
OleDbDataReader Reader = cmd1.ExecuteReader();
while (Reader.Read())
{
if (Reader[5].ToString() == "manager")
{
this.Hide();
Student_Info stuInf = new Student_Info();
stuInf.Show();
break;
}
else if (Reader[5].ToString() == "employee")
{
MessageBox.Show("log in as a employee ");
}
else
{
MessageBox.Show("Inviled User name or password");
}
}
myConnection.Close();
}

Your else statement isn't executed because there are no values to read when an invalid username or password is entered. You need to check if your reader has any rows. See here
Code
//Are there any rows
if(Reader.HasRows)
{
//If so read them
while (Reader.Read())
{
if (Reader[5].ToString() == "manager")
{
this.Hide();
Student_Info stuInf = new Student_Info();
stuInf.Show();
break;
}
else if (Reader[5].ToString() == "employee")
{
MessageBox.Show("log in as a employee ");
}
}
}
else
{
MessageBox.Show("Inviled User name or password");
}

Related

How can I retrieve data from mysql database

This code is from our user login profile for our SAD project. The account I register for user log in is working since it saved in the database but I can't log in because it says invalid.
private void btn_login_Click(object sender, EventArgs e)
{
conn = new MySqlConnection(myconn);
string query = "select * from southpoint_school.user where userUsername='" + textBox1.Text + "' and userPassword='" + textBox2.Text + "'";
conn.Open();
cmd = new MySqlCommand(query, conn);
MySqlDataReader reader = cmd.ExecuteReader();
int count = 0;
while (reader.Read())
{
count++;
}
if (count == 1)
{
conn = new MySqlConnection(myconn);
string problem = "SELECT userAccountType from southpoint_school.user WHERE userUsername ='" + textBox1.Text + "'";
conn.Open();
cmd = new MySqlCommand(problem, conn);
string answer = cmd.ExecuteScalar().ToString();
conn.Close();
MessageBox.Show("Login successful!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
if (answer == "Administrator")
{
memorable = "Administrator";
frm_main main = new frm_main();
main.Show();
this.Hide();
}
else
{
memorable = "Limited";
frm_main main = new frm_main();
main.Show();
this.Hide();
}
}
else if (textBox1.Text == "" && textBox2.Text == "")
{
MessageBox.Show("No Username and/or Password Found!");
}
else
{
MessageBox.Show("Invalid Username And/Or Password!");
}
conn.Close();
}
The case
Invalid Username And/Or Password!
can only happen when you have 0 ore more than 1 search results in your southpoint_school.user database with your entered username + password. So I would inspect the data in your database.
Additionally I would
use parameters instead of string-concatenation for creating sql statements to avoid injection
save (salted)hashed passwords instead of plaintext in your database
use using statements for more effecient ressurce useage
query the user-table only once and use the result twice
e.g.:
if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text))
{
MessageBox.Show("No Username and/or Password Found!");
}
else
{
DataTable dtResult = new DataTable();
string Command = "select * from southpoint_school.user where userUsername=#un and userPassword=#up";
using (MySqlConnection myConnection = new MySqlConnection(ConnectionString))
{
using (MySqlDataAdapter myDataAdapter = new MySqlDataAdapter(Command, myConnection))
{
myDataAdapter.SelectCommand.Parameters.Add(new MySqlParameter("#un", textBox1.Text));
myDataAdapter.SelectCommand.Parameters.Add(new MySqlParameter("#up", textBox2.Text));
myDataAdapter.Fill(dtResult);
}
}
if (dtResult.Rows.Count == 1)
{
MessageBox.Show("Login successful!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
if ((string)dtResult.Rows[0]["userAccountType"] == "Administrator")
{
memorable = "Administrator";
frm_main main = new frm_main();
main.Show();
this.Hide();
}
else
{
memorable = "Limited";
frm_main main = new frm_main();
main.Show();
this.Hide();
}
}
else if (dtResult.Rows.Count == 0)
{
MessageBox.Show("Invalid Username And/Or Password!");
}
else //TODO: treat the case for multiple results
{
}
}

Messagebox doesn't show

I've created a database using mysql, on my form1 there are two textboxes username and password and a login button. My program retrieves information from database and if the data s matches it logs in else an messagebox should pop up telling that username of password is wrong ( which it doesn't show)
before posting the code:
I've declared: the following
public int logid;
public int loginid(strign name) // to set logid the id of the user
public void loginfun(); // checks the data and logs in if id and password matches, else should give an error message.
and my code is as follows:
public int loginid(string name)
{
string conString = "Server=localhost;Database=ozturk;Uid=_____;pwd=_____";
MySqlConnection mcon = new MySqlConnection(conString);
string getid = "SELECT username,id from ozturk.admin WHERE username='" + name + "'";
MySqlCommand cmd = new MySqlCommand(getid, mcon);
MySqlDataReader myReader;
mcon.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
if (myReader["username"].ToString() == name)
{
return Convert.ToInt32(myReader["id"].ToString());
}
}
return 0;
}
public void loginfun()
{
string conString ="Server=localhost;Database=ozturk;Uid=_____;pwd=_____";
MySqlConnection mcon = new MySqlConnection(conString);
string selectCommand = "SELECT * FROM ozturk.admin";
MySqlCommand cmd = new MySqlCommand(selectCommand,mcon);
MySqlDataReader myReader;
mcon.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
try
{
if (myReader["username"].ToString() == txtuserid.Text && myReader["password"].ToString() == txtpassword.Text)
{
// set logid to userid
logid = loginid(myReader["username"].ToString());
string updateCommand = "UPDATE ozturk.admin SET status = 'on' WHERE id='" + logid + "' ";
MySqlConnection newcon = new MySqlConnection(conString);
MySqlCommand cmd2 = new MySqlCommand(updateCommand, newcon);
MySqlDataReader myReader2;
newcon.Open();
myReader2 = cmd2.ExecuteReader();
Anasayfa anasayf = new Anasayfa();
anasayf.Show();
this.Hide();
}
}
catch (Exception)
{
MessageBox.Show("Username or Password is incorrect");
throw;
}
}
}
The problem is: My program logs in and opens the other form if the username and the password is correct however it doesn't do anything if the username or password is wrong, What am I missing here? any help is appreciated
Thanks
I've solved the problem, here is what I've done: I've changed my login function from void to bool: here is the latest code:
public bool loginfun()
{
string conString ="Server=localhost;Database=ozturk;Uid=_____;pwd=_____";
MySqlConnection mcon = new MySqlConnection(conString);
string selectCommand = "SELECT * FROM ozturk.admin";
MySqlCommand cmd = new MySqlCommand(selectCommand,mcon);
MySqlDataReader myReader;
mcon.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
try
{
if (myReader["username"].ToString() == txtuserid.Text && myReader["password"].ToString() == txtpassword.Text)
{
// giriş yapan kişinin id si
logid = loginid(myReader["username"].ToString());
string updateCommand = "UPDATE ozturk.admin SET status = 'on' WHERE id='" + logid + "' ";
MySqlConnection newcon = new MySqlConnection(conString);
MySqlCommand cmd2 = new MySqlCommand(updateCommand, newcon);
MySqlDataReader myReader2;
newcon.Open();
myReader2 = cmd2.ExecuteReader();
return true;
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
throw;
}
}
return false;
}
and inside the login button the code is as follows:
if (loginfun() == true)
{
Anasayfa anasayf = new Anasayfa();
anasayf.Show();
this.Hide();
}
else
{
MessageBox.Show("Username or Password is incorrect");
}
Thank you everyone for the tips
This is your code:
bool flag = false;
while (myReader.Read())
{
try
{
if (myReader["username"].ToString() == txtuserid.Text && myReader["password"].ToString() == txtpassword.Text)
{
// set the flag to true, is credentials match and break from the loop
flag = true;
break;
// set logid to userid
logid = loginid(myReader["username"].ToString());
string updateCommand = "UPDATE ozturk.admin SET status = 'on' WHERE id='" + logid + "' ";
MySqlConnection newcon = new MySqlConnection(conString);
MySqlCommand cmd2 = new MySqlCommand(updateCommand, newcon);
MySqlDataReader myReader2;
newcon.Open();
myReader2 = cmd2.ExecuteReader();
Anasayfa anasayf = new Anasayfa();
anasayf.Show();
this.Hide();
}
}
catch (Exception)
{
MessageBox.Show("Username or Password is incorrect");
throw;
}
}
if(!flag)
{
MessageBox.Show("Username or Password is incorrect");
}

how to add restrictions in login form?

i'm creating a login form for my system and want to add a User and Admin account. what i did in my database is to create a table for my users with a specific user type U_Type would be either 1 = admin or 2 = user.
i want to add an if statement that would call my column name U_Type and compare it either 1 or 2. below is my unfinished code. i'm using visual studio 2008 c# and ms sql 2005
here is my code:
float Outcome;
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True";
conn.Open();
String txtUser = textBox1.Text;
String txtPass = textBox2.Text;
string query = "SELECT * FROM tblUsers WHERE U_Name=#U_Name AND U_Pass=#U_Pass AND U_Type=#type";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.Add(new SqlParameter("#U_Name", txtUser));
cmd.Parameters.Add(new SqlParameter("#U_Pass", txtPass));
cmd.Parameters.Add(new SqlParameter("#type", type));
SqlDataReader dr = cmd.ExecuteReader();
if (textBox1.Text.Trim().Length == 0)
{
MessageBox.Show("Login Failed");
Outcome = Convert.ToInt32(lblOutcome.Text);
Outcome = Outcome - 1;
textBox1.Clear();
textBox2.Clear();
lblOutcome.Text = Outcome.ToString();
if (Outcome == 0)
{
MessageBox.Show("You have reached the maximum number of trial");
this.Close();
}
}
else if (textBox2.Text.Trim().Length == 0)
{
MessageBox.Show("Login Failed");
Outcome = Convert.ToInt32(lblOutcome.Text);
Outcome = Outcome - 1;
textBox1.Clear();
textBox2.Clear();
lblOutcome.Text = Outcome.ToString();
if (Outcome == 0)
{
MessageBox.Show("You have reached the maximum number of trial");
this.Close();
}
}
else if (dr.HasRows == true)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True";
SqlCommand command = new SqlCommand("SELECT U_Name ='"+textBox1.Text+"', U_Pass = '" +textBox2.Text+"', U_Type = 1 FROM tblUsers",con);
con.Open();
SqlDataReader sdr = command.ExecuteReader();
if ()
{
MessageBox.Show("Login Successful");
MDIParent1 settingsForm = new MDIParent1();
settingsForm.Show();
this.Hide();
}
else
{
MessageBox.Show("Login Successful");
MDIParent2 settingsForm = new MDIParent2();
settingsForm.Show();
this.Hide();
}
}
else
{
MessageBox.Show("Login Failed");
Outcome = Convert.ToInt32(lblOutcome.Text);
Outcome = Outcome - 1;
textBox1.Clear();
textBox2.Clear();
lblOutcome.Text = Outcome.ToString();
if (Outcome == 0)
{
MessageBox.Show("You have reached the maximum number of trial");
this.Close();
}
}
}
i want the if statement to be here
else if (dr.HasRows == true)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True";
SqlCommand command = new SqlCommand("SELECT U_Name ='"+textBox1.Text+"', U_Pass = '" +textBox2.Text+"', U_Type = 1 FROM tblUsers",con);
con.Open();
SqlDataReader sdr = command.ExecuteReader();
if ("#type"==1)
{
MessageBox.Show("Login Successful");
MDIParent1 settingsForm = new MDIParent1();
settingsForm.Show();
this.Hide();
}
else
{
MessageBox.Show("Login Successful");
MDIParent2 settingsForm = new MDIParent2();
settingsForm.Show();
this.Hide();
}
}
i really don't know the proper syntax for it. help me please i would really appreciate it. thank you
You have, roughly, the right idea, but your implementation is off.
You're validating the text boxes after you send the SQL query but before you check the results, and you're also passing in the type of the user.
The user type should be stored in the database along with the user, and you can return the type of user for the matching row (based on username and password). And your syntax is way off in some places.
A simplified approach based on what you appear to be doing would be something like this:
Do validation on the text boxes before executing the command. If validation passes, then select the row that matches the user name and password, and process the results accordingly:
private void button1_Click(object sender, EventArgs e)
{
bool validInput = false;
if (!String.IsNullOrWhitespace(textBox1.Text))
{
validInput = true;
}
else
{
MessageBox.Show("Please enter a user name.");
}
if (!String.IsNullOrWhitespace(textBox2.Text))
{
validInput = true;
}
else
{
MessageBox.Show("Please enter a password.");
}
if (validInput)
{
using (SqlConnection conn = new SqlConnection("Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True"))
{
conn.Open();
SqlCommand command = new SqlCommand("SELECT * FROM tblUsers WHERE U_Name = #U_Name AND U_Pass = #U_Pass", conn);
command.Parameters.Add("#U_Name", SqlDbType.VarChar).Value = textBox1.Text;
command.Parameters.Add("#U_Pass", SqlDbType.VarChar).Value = textBox2.Text;
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
string userType = reader["U_type"].ToString();
if (userType == "1")
{
// Handle regular users
}
else if (userType == "2")
{
// Handle admin users
}
}
else
{
MessageBox.Show("Login failed.");
}
}
}
}
}
The above code illustrates the approach. If both text boxes have text in them, the validInput flag is set to true. The connection is then opened, the command and parameters are set, the command is executed and a reader returned. If the reader has rows (meaning 1 or more records that matched the username and password are found), the reader is advanced to the first record (there should be only one match for a given username/password combination).
The "U_type" column is interrogated to see if it's a regular user or an admin user, and the user is processed accordingly.
It's not clear from your posted code whether "U_type" is a string or an integer; if it's an integer you'll need to convert it like this:
int userType = Convert.ToInt32(reader["U_type"]);
And change the corresponding if checks:
if (userType == 1)
and
if (userType == 2)
If you want to authenticate user and compare the Type then return DataTable.
public DataTable ValidateUser(string username,string password)
{
DataTable dt = new DataTable();
SqlCommand cmd; SqlDataReader dr;
SqlConnection con = new SqlConnection(yourConnectionString);
try
{
cmd = new SqlCommand();
cmd.CommandText = "Select * from tblUsers where U_Name=#U_Name and U_Pass=#U_Pass";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#U_Name", username);
cmd.Parameters.AddWithValue("#U_Pass", password);
cmd.Connection = con;
if (con.State == ConnectionState.Closed)
{
con.Open();
}
dr = cmd.ExecuteReader();
dt.Load(dr);
}
catch (Exception ex)
{
dt = null;
}
finally
{
if (con.State != ConnectionState.Closed)
{
con.Close(); con.Dispose();
}
}
return dt;
}
Calling ValidateUser Method:
DataTable dt=new DataTable();
dt=ValidateUser();
if(dt!=null && dt.Rows.Count>0)
{
if(Convert.ToInt32(dt.Rows.[0]["U_Type"])==1)
{
//show form for user where utpe=1
}
else if(Convert.ToInt32(dt.Rows.[0]["U_Type"])==2)
{
//show form for user where utype=1
}
else
{
//otherstuff
}
}
else
{
//invwalid user
}
hopethis helps

using IF condition inside a while loop in C#

I have a problem with my C# code. I have created a login form in C# 2010. When I am validating the user name, I used an if-condition inside the while loop but the thing is that even when the username and password are correct, it executes the else-statement. Please help me to solve this.
Here is my code :
private void btnlogin_Click(object sender, EventArgs e) {
string connection=
#"Data Source=.\SQLEXPRESS;"
+" AttachDbFilename=|DataDirectory|ResturantDB.mdf;"
+" Integrated Security=True; User Instance=True";
SqlConnection cn=new SqlConnection(connection);
try {
cn.Open();
}
catch(Exception) {
// print the exception's message?
MessageBox.Show("Connection to Database failed; check Connection!");
}
SqlCommand cmd=new SqlCommand("SELECT * FROM [Login]", cn);
cmd.Connection=cn;
SqlDataReader reader=null;
reader=cmd.ExecuteReader();
while(reader.Read()) {
if(
txtuser.Text==(reader["Username"].ToString())
&&
txtpass.Text==(reader["Password"].ToString())
) {
//MessageBox.Show( "logged in!" );
Home newhome=new Home();
newhome.Show();
this.Hide();
}
else {
MessageBox.Show("Incorrect credentials!");
}
}
}
you should use a break, when a username is found in your if condition like
bool found = false;
while (reader.Read())
{
if (txtuser.Text == (reader["Username"].ToString()) && txtpass.Text == (reader["Password"].ToString()))
{
//MessageBox.Show("loged in!");
Home newhome = new Home();
newhome.Show();
this.Hide();
found = true;
break;
}
}
if (!found)
MessageBox.Show("Incorrect credentian..!");
you get into the else block because if any login is not correct, the messagebox appears and that is in n-1 cases in your code.
You're checking if all users have the same user name and password. You need to refine your SQL to select only that one user. Also, please read into password hashing for the sake of your users.
Because its in a loop.
create a bool variable. update its value in loop (if found same username and password) and check outside based on its value.
Do this
bool found;
while (reader.Read())
{
if (txtuser.Text == (reader["Username"].ToString()) &&
txtpass.Text == (reader["Password"].ToString()))
{
found = true;
break;
}
}
if (found)
{
MessageBox.Show("loged in!");
Home newhome = new Home();
newhome.Show();
this.Hide();
}
else
{
MessageBox.Show("Incorrect credentian..!");
}
I will solve it on this way:
private void btnlogin_Click(object sender, EventArgs e)
{
string connection = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|ResturantDB.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(connection);
try
{
cn.Open();
}
catch (Exception)
{
MessageBox.Show("Conncetion to Database faild check Connection !");
}
while (true)
{
SqlCommand cmd = new SqlCommand("SELECT [Password] FROM [Login] WHERE [Username] = '" + txtuser.Text + "'", cn);
cmd.Connection = cn;
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
if (!reader.HasRows)
MessageBox.Show("User does not exist. Please, try again.");
else
{
//username should be unique, so only one row is possible to have
reader.Read();
if (txtpass.Text == (reader["Password"].ToString()))
{
//MessageBox.Show("loged in!");
Home newhome = new Home();
newhome.Show();
this.Hide();
return;
}
else
MessageBox.Show("Incorrect credentian..! Try again.");
}
}
}
Simplest and Secure method
SqlCommand cmd = new SqlCommand("Select uname, pswd from [Login] where uname =#uname and pswd =#ps", conn);
cmd.Parameters.Add(new SqlParameter("#uname", "username here"));
cmd.Parameters.Add(new SqlParameter("#ps", "pasword here"));
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
//MessageBox.Show( "logged in!" );
Home newhome = new Home();
newhome.Show();
this.Hide();
}
else
{
MessageBox.Show( "Incorrect credentials!" );
}
No need to loop thru the records for your case
use this query, compate username and password in the query:
"SELECT * FROM [Login] where Username='" + txtuser.Text "' and password = '" + txtpass.Text + "'"

form validation using c# and sql commands

i am trying to make a windows form to log into another one,
i am using a database with users and passwords
the code is as follows:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=mmtsql.XXX.XXXX.XX.XX;Initial Catalog=mmtXX-XXX;User ID=mmtXX-XXX;Password=mmtXX-XXX");
conn.Open();
SqlCommand mycommand = new SqlCommand("SELECT User, Password FROM UsersData WHERE User = '" + textBox1.Text + "' and Password = '" + textBox2.Text + "'", conn);
SqlDataReader reader = mycommand.ExecuteReader();
if(reader != null)
{
if(reader.Read())
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
}
else
{
label3.Text = "Invalid Username or Password !";
}
the problem that a getting is that no matter what i insert into the textboxes, right or wrong i am getting:
Invalid Username or Password !
is there anyway to fix my code?
regards;
I would do it this way, keeping to the method you are using:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(conn_str);
conn.Open();
string sql = "SELECT User, Password
FROM UsersData WHERE User=#user and Password=#password"
SqlCommand mycommand = new SqlCommand(sql, conn);
//parameterize your query!
mycommand.Parameters.AddWithValue("user", txtuser.text);
mycommand.Parameters.AddWithValuye("password", txtpassword.password);
SqlDataReader reader = mycommand.ExecuteReader();
if(reader == null)
{
label3.Text = "Database query failed!";
}
else if(reader.HasRows)
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
Use parameterized queries as they will help you against sql injection as mentioned by SLaks.
Change your code to below
using (SqlCommand command = new SqlCommand("SELECT User, Password
FROM UsersData WHERE User=#user and Password=#password", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("user ", textbox1.text));
command.Parameters.Add(new SqlParameter("password", textbox2.text));
SqlDataReader reader = command.ExecuteReader();
if (reader == null)
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
}

Categories