Is there a way to check if I'm on the last record ? thanks
You don't need the . Close() statement in either sample: it's handled by the . Dispose() call.
To retrieve data using a DataReader, create an instance of the Command object, and then create a DataReader by calling Command. ExecuteReader to retrieve rows from a data source.
SqlDataReader is the fastest way. Make sure you use the get by ordinal methods rather than get by column name. e.g. GetString(1);
The HasRows property may help you. Type: System. Boolean true if the SqlDataReader contains one or more rows; otherwise false. Save this answer.
Use this pattern to identify and process the last row in result:
if (reader.Read())
{
var loop = true;
while (loop)
{
//1. Here retrive values you need e.g. var myvar = reader.GetBoolean(0);
loop = reader.Read();
if (!loop)
{
//You are on the last record. Use values read in 1.
//Do some exceptions
}
else {
//You are not on the last record.
//Process values read in 1., e.g. myvar
}
}
}
Other than "there isn't another one afterwards", no. This may mean you need to buffer the row, try to read, then look at the buffered data if it turned out to be the last.
In many cases, when the data is moderate and you are building an object model of some kind, you can just looks at the constructed data, i.e. make a List<T>
of all the rows when using the reader, then after that, look at the last row in the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With