Search code examples
c#asp.netsqldatareaderdatareader

Datareader not displaying first row


I am looping through my database to display a list of leagues a player is associated with. If a player is not a member of any leagues then a message displays to tell them.

Here is the code

if (dReader.Read())
{          
    while (dReader.Read())
    {
        usersLeagues.Text += "<li class=\"li-myLeagues\"><a  href=\"leagueDetails.aspx?leagueID=" + (dReader["leagueID"].ToString()) + "\">" + (dReader["leagueName"].ToString()) + "</a></li>";
    }
}
else
{
    usersLeagues.Text = "You are currently not a part of any leagues";
}
dReader.Close();
conn.Close();

The issue is that the data reader is not displaying the first league in the query.

Any idea why this is?


Solution

  • Change

    if (dReader.Read()){  
    

    to

    if (dReader.HasRows){
    

    By calling the Read() in the if statement, you actually are reading the first row of data. Calling Read() again in the while statement, skips the first read row.

    You can use HasRows property to check if the reader contains any data.