执行C#数据库查询代码时遇System.Int32转System.String异常求助
解决Unable to cast object of type 'System.Int32' to type 'System.String'异常
这个问题的根源很清晰——你数据库里的billno字段是整数类型(Int32),但你在代码里用reader.GetString(0)尝试直接读取它,这就触发了类型不匹配的转换异常。
给你两种简单的修复方案,按需选择:
- 在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;
- 在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
相关产品推荐
相关产品推荐

