2016-04-18 233 views
0

,我發現了以下錯誤:登錄名和密碼程序

An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll Additional information: There is no row at position 0.

我已經貼上我的代碼,我不能弄清楚爲什麼我收到此錯誤信息。

我知道這是一個非常基本的程序,但我只是在學習。 :)

SqlConnection con = new SqlConnection(@"Data Source=B70143272PC4;Initial Catalog=TestDB1;Integrated Security=True"); 

SqlDataAdapter sda = new SqlDataAdapter("select employeeid,username, password from Employeeinfo where [UserName] = '" + textBox1+ "' and [Password] = '" +textBox2.Text+"'", con); 

DataTable dt = new DataTable(); 
sda.Fill(dt); 

if (dt.Rows[0][0].ToString() == "1") 
{ 
    this.Hide(); 
    Form2 ff = new Form2(); 
    ff.Show(); 
} 
else 
{ 
    MessageBox.Show("Please check your Username and Passowrd"); 
} 

回答

1

你錯過了TextBox1Text財產。它應該是:

SqlDataAdapter sda = new SqlDataAdapter("select employeeid,username, password from Employeeinfo where [UserName] = '" + textBox1.Text+ "' and [Password] = '" +textBox2.Text+"'", con); 

但你應該總是使用parameterized queries避免SQL Injection。就像這樣:

SqlDataAdapter sda = new SqlDataAdapter("select employeeid,username, password from Employeeinfo where [UserName] = @username and [Password] = @password", con); 
sda.SelectCommand.Parameters.AddWithValue("@username", textBox1.Text); 
sda.SelectCommand.Parameters.AddWithValue("@password", textBox2.Text); 
0

另外,如果我理解這個正確,要檢查的,而不是if (dt.Rows[0][0].ToString() == "1")

使用if (dt.Rows.Count == 1)

行,如果表具有任何結果,有,告訴你一個計數屬性集合中有多少行。