How to solve error `You have specified an invalid column ordinal`

Harvey picture Harvey · May 27, 2013 · Viewed 8.8k times · Source

I am getting the following error:

You have specified an invalid column ordinal

I already checked the column number in my database and I know it's right. Here's my code:

using (MySqlCommand cmd = new MySqlCommand(query, con))
{

    cmd.Parameters.AddWithValue("@ID", txtboxID.Text);
    MySqlDataReader dr = cmd.ExecuteReader();

    while(dr.Read())
    {
        int size = dr.GetInt32(3);
        int quantity = dr.GetInt32(4);
        string variant = dr.GetString(2);

        DataGridViewRow row = dataGridView2.Rows
           .Cast<DataGridViewRow>()
           .Where(r => (r.Cells["variant_name"].Value.ToString().Equals(variant) && r.Cells["size"].Value.Equals(size)))
           .First();

        row.Cells["quantity"].Value = quantity;
    }
}

I'm getting the error on this line -> int size = dr.GetInt32(3);

Answer

Tim picture Tim · May 27, 2013

Your query is returning three columns, and the column ordinal is 0 based, so your ordinals would be 0, 1, and 2, like this:

int size = dr.GetInt32(1);
int quantity = dr.GetInt32(2);
string variant = dr.GetString(0);

As your query returns variant_name, size and quantity in that order (0, 1, and 2).