1

I am getting compile-time error at reader.GetString, any idea why?

Code:

using (var connection = new OleDbConnection())
{
    connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Sparrow vivek\Documents\Billing.accdb";
    connection.Open();
    var query = "SELECT ItemCode FROM invoice";
    using (var command = new OleDbCommand(query, connection))
    {
        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                comboBox1.Items.Add(reader.GetString("ItemCode"));
                comboBox2.Items.Add(reader.GetString("ItemCode"));
            }
        }
    }
}

enter image description here

4
  • Have you tried comboBox1.Items.Add(reader.GetString(0));? Commented Dec 15, 2014 at 14:53
  • have you tried comboBox1.Items.Add(reader("ItemCode").toString());? Commented Dec 15, 2014 at 14:54
  • the best overloaded method match for system.data.common.DbDataReader.GetString(int) has some invalid arguments Commented Dec 15, 2014 at 14:54
  • "Any idea why?" Yes, you're passing invalid arguments to DbDataReader.GetString(int). Exactly as the error message says! Commented Dec 15, 2014 at 14:55

2 Answers 2

4

OleDbDataReader.GetString method takes int as a parameter, not string.

public override string GetString(
    int i
)

It takes the zero-based column number.

Since you get just one column, change it to;

while (reader.Read())
{
    comboBox1.Items.Add(reader.GetString(0));
    comboBox2.Items.Add(reader.GetString(0));
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is not SqlDataReader.
2

OleDbDataReader.GetString requires an input of int. It expects the column ordinal, not the column name.

Either use the column ordinal directly, or determine the ordinal ahead of time. You can determine the column ordinal by using OleDbDataReader.GetOrdinal:

comboBox1.Items.Add(reader.GetString(reader.GetOrdinal("ItemCode")));

Since you are doing this in a loop, you could do something like this:

int itemCodeOrdinal = reader.GetOrdinal("ItemCode");
while (reader.Read())
{
    comboBox1.Items.Add(reader.GetString(itemCodeOrdinal));
    comboBox2.Items.Add(reader.GetString(itemCodeOrdinal));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.