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

しかし、あなたは常にSQL Injectionを避けるためにparameterized queriesを使用する必要があります:それはする必要があります。 if (dt.Rows.Count == 1)

行を、私はこれを正しく理解し、あなたの代わりにif (dt.Rows[0][0].ToString() == "1")

使用の、データテーブルは、任意の結果を持っているかどうかを確認したい場合は

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

はまた、あなたを伝えるcountプロパティがあります。このようなコレクション内の行数。