0

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

Tim
  • 28,212
  • 8
  • 63
  • 76
Harvey
  • 399
  • 4
  • 15
  • 31
  • In which of these lines do you get this? – Nikhil Agrawal May 27 '13 at 01:23
  • Can you show the code where `dr` is instantiated? Based on the error is sounds like there may not be any rows in it, or you didn't call `dr.Read` on it. – Tim May 27 '13 at 01:34
  • @Tim. I've updated the code I've already included the code where `dr` is instantiated. – Harvey May 27 '13 at 01:42
  • Are you sure the query is returning results? Have you run the query in SQL Server (or whatever your SQL of choice is)? – Tim May 27 '13 at 01:42
  • @Tim I'm not sure if its returning results. Anyway, how would I know? – Harvey May 27 '13 at 01:45
  • Based on your error, I'd say it's returning results other than what you expected. It looks like you're using `MySQL` - I believe there's a GUI control panel that you can run the query in to see if it gives results. Can you post your query and the table structure? The query is returning something, otherwise the `while` loop would never be entered. – Tim May 27 '13 at 01:47
  • 1
    @Tim Here is the query `string query = "SELECT variant_name, size, quantity FROM tblOrder_Products WHERE order_ID=@ID";` – Harvey May 27 '13 at 02:00
  • 2
    Your ordinals are off - variant should be 0, size should be 1 and quantity should be 2. The ordinal is 0 based. – Tim May 27 '13 at 02:01
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/30662/discussion-between-harvey-and-tim) – Harvey May 27 '13 at 02:06

1 Answers1

2

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).

Tim
  • 28,212
  • 8
  • 63
  • 76
  • Okay I know now. Because, at first I'm a little confuse if that ordinal is based on the column number in my database. Thank you again. – Harvey May 27 '13 at 02:19