Else在使用c#的阅读器中不起作用

时间:2015-09-19 02:40:34

标签: c#

当我输入用户名和密码时,它会成功登录并打开所需的字段但是当我输入错误的名称或密码(未保存在DB中)时,它实际上没有显示它应该遇到“else”这是代码

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

1 个答案:

答案 0 :(得分:3)

您的else语句未执行,因为输入的用户名或密码无效时无法读取值。您需要检查您的阅读器是否有任何行。见here

<强>代码

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