C#多级用户登录

时间:2015-09-25 00:46:27

标签: c# login

您好我尝试进行多级登录,所以我使用此代码,但它不起作用

  

System.Data.dll中出现未处理的“System.InvalidOperationException”类型异常

     

附加信息:没有数据时读取的尝试无效。

错误显示在string s1 = dr[3].ToString();

CODE:

private void button3_Click(object sender, EventArgs e)
 {
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = @"Server=GATEWAY-PC\SQLSERVER;Initial Catalog=train_system;Integrated Security=True";
    SqlCommand cmd = new SqlCommand("SELECT * FROM employer WHERE username='" + textBox1.Text + "'AND password='" + textBox2.Text + "'",conn);

    conn.Open();

    SqlDataReader dr ;
    dr = cmd.ExecuteReader();


    int count = 0;
    while (dr.Read())
    {
       count += 1;
    }

    if (count == 1)
    {
       string s1 = dr[3].ToString();

       if ( s1 == "1")
       {
          MessageBox.Show("Login as Shedule");
       }
       else if (s1 == "2")
       {
          MessageBox.Show("Login as Operation");
       }
    }
    else if (count < 1)
    {
       MessageBox.Show("error");
    }
}

2 个答案:

答案 0 :(得分:0)

错误显然是dr[3]不存在!

使用调试工具查找执行第dr行时string s1 = dr[3].ToString();中的内容

答案 1 :(得分:0)

你可以像这样重写它

if (dr.Read())
{
   string s1 = dr[3].ToString(); //this line tries to get 4th column. So, your query should return 4 columns.

   if ( s1 == "1")
   {
      MessageBox.Show("Login as Shedule");
   }
   else if (s1 == "2")
   {
      MessageBox.Show("Login as Operation");
   }
}
else
{
   MessageBox.Show("error");
}