Check if it's the last record in sqldatareader

wben picture wben · Jul 28, 2012 · Viewed 20k times · Source

Is there a way to check if I'm on the last record ? thanks

Answer

Raman Zhylich picture Raman Zhylich · Jul 28, 2012

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
        }
    }
}