I'm getting the following error:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll Additional information: There is no row at position 0.
I have pasted my code and I cant figure why I'm receiving this error message.
I know this is a very basic program but I'm just learning. :)
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");
}
You missed the Text
property of the TextBox1
. It should be:
SqlDataAdapter sda = new SqlDataAdapter("select employeeid,username, password from Employeeinfo where [UserName] = '" + textBox1.Text+ "' and [Password] = '" +textBox2.Text+"'", con);
But you should always use parameterized queries to avoid SQL Injection . Like this:
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);
Also, if I understood this correctly and you want to check if the datatable has any results, instead of if (dt.Rows[0][0].ToString() == "1")
use if (dt.Rows.Count == 1)
Rows has a count property that tells you how many rows there are in the collection.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.