2015-09-25 74 views
0

嗨,我儘量讓多級別的登錄,所以我用這個代碼,但它不工作C#多級用戶登錄

「System.InvalidOperationException」類型發生在System.Data未處理的異常.dll文件

其他信息:無效嘗試時不存在數據讀取。

錯誤是表現出對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"); 
    } 
} 
+0

請出示僱主表的模式 – DarkKnight

回答

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

由於它的工作! :) –

0

錯誤明顯是說dr[3]不存在!

使用調試工具,找出哪些是dr在執行行string s1 = dr[3].ToString();