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

Devin Prejean picture Devin Prejean · Feb 15, 2012 · Viewed 12.6k times · Source

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();
    }

Answer

dsolimano picture dsolimano · Feb 15, 2012

reader[0] accesses the first field from the reader, not the first row. Check out the sample code from MSDN.

// Call Read before accessing data.
while (reader.Read())
{
    Console.WriteLine(String.Format("{0}, {1}",
            reader[0], reader[1]));
}

This writes out the first and second columns of each row.

Also, I'm not really sure why you're not using a using statement, and why you're calling ExecuteReader in the finally block - those both look odd.