简体   繁体   中英

Datareader error while converting string to int

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

在此处输入图片说明

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM