2016-04-18 188 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)

行,如果表具有任何结果,有,告诉你一个计数属性集合中有多少行。