SqlDataReader [0] is empty
I'm wanting to display the first row of a SqlDataReader
(its the only row/column the database returns) in a text field. I thou开发者_如何学JAVAght 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.
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.
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. *
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.
精彩评论