0

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.";
}
marc_s
759k185 gold badges1.4k silver badges1.5k bronze badges
asked May 5, 2016 at 14:22

5 Answers 5

2

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

answered May 5, 2016 at 14:24
Sign up to request clarification or add additional context in comments.

Comments

2

You need to call Read method on reader.

eg.

while (reader.Read()) 
{
 ....
}

More info in MSDN.

answered May 5, 2016 at 14:26

Comments

2

I Would do this:

 while (Reader.HasRows()) 
{ 
 Reader.Read();
 string ID = Reader["ID"].ToString();
 ...
}
answered May 5, 2016 at 14:32

Comments

1

Use if (reader.Read()) instead of if (Reader.HasRows)

answered May 5, 2016 at 14:26

Comments

-1

Yeah. You never READ.

while (Reader.Read ()) { }

instead of If hasrows.

You must call Read. Like every tutorial shows.

answered May 5, 2016 at 14:25

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.