C# Retrieve ALL SQL Query Results

Kajin
else if (listBox1.SelectedIndex == 1)
{
    String sql2 = "SELECT FirstName, LastName FROM Players WHERE Team = 'Milwaukee Bucks'" +
                  "AND Number < 24";
    // command statement
    command = new SqlCommand(sql2, cnn);
    SqlDataReader reader = command.ExecuteReader();

    // Get table values
    if (reader.Read())
    {
        textBox1.Text = reader.GetString(0).ToString() + " " + reader.GetString(1).ToString();
    }
    cnn.Close();
    command.Dispose();
}

Above is a section of my code. I have a list box with options for the user to choose, and based on which item is selected, a display button will run a query and return the results to a textbox.

However, when I run the code I am only getting one result back. The query returns players on the Bucks who have a number less than 24. There should be multiple of them but I am only getting one in my C# application.

Jawad

You need to use a while loop to read all the lines instead of reading a single line (via Read()).

Microsoft Documentation has an example of how to use the while loop.

StringBuilder sb = new StringBuilder()
while (reader.Read())
{
    sb.AppendLine(reader.GetString(0).ToString() + " " + reader.GetString(1).ToString());
}
textBox1.Text = sb.ToString();

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related