繁体   English   中英

将字符串转换为int时出现Datareader错误

[英]Datareader error while converting string to int

我在reader.GetString遇到编译时错误,知道为什么吗?

码:

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方法采用int作为参数,而不是string

public override string GetString(
    int i
)

它采用从零开始的列号。

由于您只有一列,因此将其更改为;

while (reader.Read())
{
    comboBox1.Items.Add(reader.GetString(0));
    comboBox2.Items.Add(reader.GetString(0));
}

OleDbDataReader.GetString需要输入int 它需要列序号,而不是列名。

直接使用列序数,或提前确定序数。 您可以使用OleDbDataReader.GetOrdinal确定列序:

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

由于您是循环执行此操作,因此可以执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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