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

C# WinForms中无法将System.Int32转为System.String异常排查

问题原因及解决方法

核心问题

你遇到的Unable to cast object of type System.Int32 to type System.String异常,是因为用lector.GetString(index)读取了数据库中**整数类型(Int32)**的列。GetString仅能读取字符串类型列,强行读取整数类型会触发类型转换失败。

具体修正方案

1. 匹配列类型调用对应读取方法

先确认TablaPractica21表的列类型,比如列0是整数ID、列1是字符串、列2是整数类型,需对应使用GetInt32读取后转成字符串:

private void frmPractica21_Load(object sender, EventArgs e)
{
    try
    {
        conexion.Open();
        SqlCommand comando = new SqlCommand("Select * from TablaPractica21", conexion);
        SqlDataReader lector = comando.ExecuteReader();
        while (lector.Read())
        {
            // 注意:原代码第三个参数重复用了索引0,大概率是笔误,这里改成索引2示例
            dgvDatos.Rows.Add(lector.GetInt32(0).ToString(), 
                              lector.GetString(1), 
                              lector.GetInt32(2).ToString());
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show($"错误详情:{ex.Message}"); // 显示具体错误更利于排查
    }
    finally
    {
        // 确保无论是否异常,数据库连接都会关闭
        if (conexion.State == System.Data.ConnectionState.Open)
        {
            conexion.Close();
        }
    }
}

2. 通用适配方案(推荐)

如果不想逐个对应列类型,可直接读取列对象并转成字符串,自动适配所有数据类型:

while (lector.Read())
{
    dgvDatos.Rows.Add(lector[0].ToString(), lector[1].ToString(), lector[2].ToString());
}

额外优化建议

  • 原代码while循环未加大括号,虽语法合法但可读性差,建议补充
  • 原代码第三个参数重复使用索引0,大概率是笔误,需对应表的实际列索引
  • 数据库连接关闭逻辑放在finally块中,避免异常时连接未释放
  • 捕获异常时不要仅显示"Error",输出具体异常信息能更快定位问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:25:28