Search code examples
c#mysqlexecutereader

Why is ExecuteReader only giving me 1 row of data back?


I have this code and its only returning the first string [0] and errors on the rest of them saying the index is out of the array which means only 1 row is getting pulled BUT I DON'T KNOW WHY!!!

MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = new MySqlCommand("SELECT email_address FROM account_info", connection);
MySqlDataReader reader;

try
{

    connection.Open();
    reader = command.ExecuteReader();
     if (reader.HasRows)
    {
        while (reader.Read())
        {
            textBox1.Text = reader[0].ToString();

            textBox2.Text = reader[0].ToString();

            textBox3.Text = reader[0].ToString();
        }


        reader.Close();
    }

Solution

  • You're only getting one row because you're only calling reader.Read() once. Each time you call Read(), the reader advances to the next row and returns true; or, when the reader advances past the last row, it returns false.

    The indexer returns data from additional columns, and you have only one column in your query; that's why index 1 and 2 are failing.

    EDIT:

    IF you're trying to loop through the reader, you need to put your three textboxes in a structure where they can be looped through as well. Simpler, but less flexible, but correct:

    if (reader.HasRows) 
    { 
        reader.Read()
        textBox1.Text = reader[0].ToString(); 
        reader.Read()
        textBox2.Text = reader[0].ToString(); 
        reader.Read()
        textBox3.Text = reader[0].ToString(); 
        reader.Close(); 
    } 
    

    more flexible:

    List<TextBox> boxes = new List<TextBox> { textBox1, textBox2, textBox3 };
    for (int index = 0; index < boxes.Count; index++)
    {
        if (!reader.Read())
        {
            break;  // in case there are fewer rows than text boxes
        }
        boxes[index] = reader[0].ToString();
    }