2

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?

2
  • Although this is purely a guess, I'll have to check the documentation for the method, I imagine you're losing the first row with your "if" conditional. You will probably need another method to see if data was returned. Commented Mar 16, 2013 at 11:28
  • 1
    Remove this if (dReader.Read()) it will work fine, no need to write this, if there is no data it will not enter while loop. Commented Mar 16, 2013 at 11:29

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

Comments

1

The if statement is reading the first record, so when you hit the while statement it has moved onto the second result.

Comments

Your Answer

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.