You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行C#数据库查询代码时遇System.Int32转System.String异常求助

解决Unable to cast object of type 'System.Int32' to type 'System.String'异常

这个问题的根源很清晰——你数据库里的billno字段是整数类型(Int32),但你在代码里用reader.GetString(0)尝试直接读取它,这就触发了类型不匹配的转换异常。

给你两种简单的修复方案,按需选择:

  1. 在C#代码中转换类型
    先以整数类型读取字段值,再转换成字符串添加到集合里:
SqlCommand cmd = new SqlCommand("select billno from tpdetail", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
AutoCompleteStringCollection MyCollection = new AutoCompleteStringCollection();
while (reader.Read())
{
    // 先读取Int32类型值,再转为字符串
    MyCollection.Add(reader.GetInt32(0).ToString());
}
textBox3.AutoCompleteCustomSource = MyCollection;
  1. 在SQL查询中直接返回字符串
    如果不想在C#里处理类型转换,可以修改SQL语句,把整数转成字符串再查询:
select CAST(billno AS VARCHAR) from tpdetail

这样原代码里的reader.GetString(0)就能正常工作了。

额外小建议:

  • 建议确认下数据库中billno字段的实际类型,避免后续再踩类似的类型匹配坑。
  • 可以加上空值检查,防止字段为NULL时抛出异常,比如:
    while (reader.Read())
    {
        if (!reader.IsDBNull(0))
        {
            MyCollection.Add(reader.GetInt32(0).ToString());
        }
    }
    

内容的提问来源于stack exchange,提问作者Mangesh Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:53:15