1

I'm wanting to display the first row of a SqlDataReader (its the only row/column the database returns) in a text field. I thought this was the correct syntax but i get 'no data' error. I can ensure that the sql query being used should definitely return an answer, i've checked it in SQL Server.

SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConnection);
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
Label1.Text = reader[0].ToString();

reader[0] doesn't seem to show anything.

3 Answers 3

4

You need to actually read the data if I remember correctly using:

reader.Read()

Which you can iterate through or just use the first value.

Sign up to request clarification or add additional context in comments.

Comments

2

You need to call read() to move to the rows. It is usually used as

   while(reader.read())
   {
        // do something
   }

In you case put reader.read() before assigning to label.

*Also remember always to close it - so use it in using block. *

Comments

0

Please read the documentation for DataReader. The indexer provides a value based on the ordinal/column number. As you have not started (or are) moving through the reader, it will be empty.

Comments

Your Answer

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.