As, the title says, SqlDataReader can't read the data it finds. I'm querying a particular table for a username to later use in adding data to another table. The reader finds results (Reader.HasRows is true), but can't read them. This is the code:
Connection.Open();
Command = new SqlCommand("SELECT ID FROM Users WHERE Username = @Username", Connection);
Command.Parameters.Add("@Username", TextBox1.Text);
SqlDataReader Reader = Command.ExecuteReader();
if (Reader.HasRows)
{
var ID = Reader[0];
Reader.Close();
Command = new SqlCommand("INSERT INTO Locations (User_ID,Location,Date) VALUES (@User_ID,@Location,GETDATE())", Connection);
Command.Parameters.Add("@User_ID", ID);
Command.Parameters.Add("@Location", TextBox2.Text);
Command.ExecuteNonQuery();
}
else
{
ErrorLabel.Text = "Username could not be found.";
}
5 Answers 5
You have to call Reader.Read() in order to advance to the next row.
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx
Comments
Comments
I Would do this:
while (Reader.HasRows())
{
Reader.Read();
string ID = Reader["ID"].ToString();
...
}
Comments
Use if (reader.Read())
instead of if (Reader.HasRows)
Comments
Yeah. You never READ.
while (Reader.Read ()) { }
instead of If hasrows.
You must call Read. Like every tutorial shows.