Else doesn't work in reader using 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();
}

Upvotes: 1

Views: 53

Answers (1)

amura.cxg
amura.cxg

Reputation: 2427

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");
}

Upvotes: 3

Related Questions