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.

abatishchev
101k88 gold badges303 silver badges443 bronze badges
asked Nov 1, 2010 at 12:03

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.

abatishchev
101k88 gold badges303 silver badges443 bronze badges
answered Nov 1, 2010 at 12:07
0
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. *

answered Nov 1, 2010 at 12:07
0
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.

answered Nov 1, 2010 at 12:08

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.