0

I'm trying to display multiple rows from a query into a literal in asp.net c#. Here is my code for doing so:

        protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["RaiseFantasyLeagueConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand("[dbo].[GetUsersLeagues]", conn);
        cmd.CommandType = CommandType.StoredProcedure;

        string userId = Membership.GetUser().ProviderUserKey.ToString();
        SqlParameter userIDParam = new SqlParameter("@userId", userId);

        cmd.Parameters.Add(userIDParam);

        conn.Open();
        SqlDataReader dReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        while (dReader.Read())
        {
            usersLeagues.Text = (dReader["LeagueName"].ToString());
        }
        dReader.Close();
        conn.Close();

    }

My issue is that the literal is only displaying one of the rows, i've tried this with a list box and all rows were displayed.

Any suggestions?

Thanks in advance!

JackofAll
  • 517
  • 4
  • 13
  • 23

1 Answers1

1

You are replacing the value of the Text property on each iteration:

while (dReader.Read())
{
    usersLeagues.Text = (dReader["LeagueName"].ToString());
}

Instead of that, you need to concatenate the values on each iteration:

while (dReader.Read())
{
   usersLeagues.Text += (dReader["LeagueName"].ToString()) + Environment.NewLine;
}

In the above example, using += causes an append to the current value of usersLeagues.Text, instead of a replacement.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • Excellent, thank you ! I get a } at the end of the results, any idea why this may be ? – JackofAll Mar 06 '13 at 12:52
  • @MattHill - Nothing jumps out from the code you posted. Could it be that you append the `}` later on? Or that this is in your database? – Oded Mar 06 '13 at 12:53
  • No I don't do either, it's strange. I can't see why either ! – JackofAll Mar 06 '13 at 13:57
  • @MattHill - Debugging is your friend at such points. Debug through the loop looking at the value of `usersLeagues.Text`. See how it changes and when you get the `}`. – Oded Mar 06 '13 at 13:58