I have a simple connection to a SQL Server that is not working. I'm trying to read data from it using a SqlDataReader in C#.
Here is the code:
bool ok = false;
SqlConnection con = new SqlConnection();
con.ConnectionString = @"********";
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("@a", uname);
cmd.Parameters.AddWithValue("@b", pass);
cmd.CommandText = @"SELECT username FROM admins WHERE pass='@b'";
cmd.Connection = con;
SqlDataReader r;
con.Open();
r = cmd.ExecuteReader();
r.Read();
string n;
n = r.GetString(0);
if (n != null)
{
ok = true;
}
con.Close();
if (ok)
{
Session["admin"] = uname;
Response.Redirect("admin_page.aspx");
}
else
{
eror.Text = "An eror occured";
Response.Redirect("index.aspx#work");
}
Note: that in the above code string "uname" and "pass" are definitely not null.
Note #2 : I did try running the r.read() in a while loop (even though it's not possible to have more then one row) ---> same result.
I tried running this code in step mode, and it appears that it breaks on this line:
n = r.GetString(0);
With this exception:
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
Additional information: Invalid attempt to read when no data is present.
I'm kinda lost here. I know that it's probably a simple thing I missed here, I just can't find it. Any ideas?
@ais not even used in your query, and your problem is that now rows are returned so you get Invalid attempt to read when no data is present