无法将类型'System.Int32'的对象转换为DataReader.GetString()中的类型'System.String' [英] Unable to cast object of type 'System.Int32' to type 'System.String' in DataReader.GetString()

查看:92
本文介绍了无法将类型'System.Int32'的对象转换为DataReader.GetString()中的类型'System.String'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将数据库中的数据添加到组合框。

I was trying to add data from a database to acombobox.

        try
        {
            SqlCeCommand com = new SqlCeCommand("select * from Category_Master", con);
            SqlCeDataReader dr = com.ExecuteReader();
            while(dr.Read()){
                string name = dr.GetString(1);
                cmbProductCategory.Items.Add(name);
            }
        }
        catch(Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.Message, System.Windows.Forms.Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

我遇到以下异常:


无法将类型为'System.Int32'的对象转换为类型为'System.String'

Unable to cast object of type 'System.Int32' to type 'System.String'

我在这里缺少什么?

推荐答案

您的列的类型不是 string 。显然是 int 。因此使用:

Your column doesn't have the type string. Apparently it's int. So use:

dr.getInt32(1).ToString()

甚至

dr.GetValue(1).ToString()

在键入数据库更改时应该更粗鲁。

which should be more roubst to type changes in the database.

作为某种一般性建议,我至少尝试遵循:

As some sort of general advice I try to follow at least:


  • 仅选择您需要的内容。这主要是出于性能原因原因,即您必须明确声明列名,从而如果您不兼容地更改架构,至少会得到一个明智的错误。

  • 使用字段名称访问字段,例如

  • Select only what you need. This has mostly performance reasons and the reason that you have to state the column names explicitly, thereby getting at least a sensible error if you change your schema incompatibly.
  • Access the fields using their names, e.g.

dr.GetGuid(dr.GetOrdinal("id"))

这样的事情也可以通过扩展方法很好地解决:

Such a thing can also be nicely solved by an extension method:

public T GetFieldValue<T>(this DbDataReader reader, string columnName)
{
    return reader.GetFieldValue<T>(reader.GetOrdinal(columnName));
}


侧面说明:包括堆栈跟踪(或至少说出代码中异常所在的行)可能对其他尝试帮助您的人很有帮助。从野外猜测中可以看出,罪魁祸首可能是什么。我的猜测是堆栈跟踪看起来像这样:

Side note: Including stack traces (or at least saying which line in your code the exception comes from) can be helpful to others trying to help you. As you can see from the wild guesses what the culprit could be. My guess would be that the stack trace looks somewhat like this:

SqlDataReader.GetString
YourCode.YourMethod

GetString 或多或少是这样的:

public string GetString(int index)
{
    return (string) GetValue(index);
}

这篇关于无法将类型'System.Int32'的对象转换为DataReader.GetString()中的类型'System.String'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆