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

如何将ComboBox中SelectedItem的DataRow值转为int?报错求助

解决C# WinForms中ComboBox绑定后SelectedItem转换int的错误

问题描述

开发C# WinForms程序时遇到异常:需求是用户选择绑定数据库的ComboBox项后,将关联数据显示到ListBox中,但尝试转换comboBox1.SelectedItem的值时,报错提示无法将DataRow转换为int。

错误原因

  1. ComboBox绑定配置错误:初始代码中DisplayMember设为"Text",但Student表大概率不存在该列,导致绑定逻辑异常,SelectedValue获取也会出现问题。
  2. 选中项类型误解:ComboBox绑定DataTable后,SelectedItem实际是DataRowView对象,直接强制转换为int必然报错;即使使用SelectedValue,若列名不匹配或类型处理不当也会触发异常。
  3. 数据库操作不规范:未使用using语句管理资源,存在连接泄漏风险;每次查询前未清空ListBox,会导致重复添加数据。

修正方案

  1. 修正ComboBox绑定配置:确保DisplayMember和ValueMember对应Student表的实际列(例如表中有ID和Name列,则DisplayMember设为"Name",ValueMember设为"ID")。
  2. 正确获取选中项ID:
    • 使用SelectedValue时,通过int.TryParse安全转换为int;
    • 若使用SelectedItem,先转为DataRowView再提取ID值。
  3. 优化数据库操作:用using语句包裹数据库相关对象,自动释放资源;每次查询前清空ListBox。
  4. 添加空值判断:避免未选择项时触发查询导致错误。

完整修正代码

public partial class Form5 : Form
{
    private readonly string _connectionString = @"Server=.\;DataBase=StudentDB;Integrated Security=SSPI";

    public Form5()
    {
        InitializeComponent();
        FillComboBox();
    }

    private void FillComboBox()
    {
        using (SqlConnection con = new SqlConnection(_connectionString))
        {
            // 仅查询绑定所需列,提升性能
            string query = "select ID, Name from Student";
            SqlDataAdapter da = new SqlDataAdapter(query, con);
            DataTable dt = new DataTable();
            da.Fill(dt);

            comboBox1.DataSource = dt;
            comboBox1.DisplayMember = "Name"; // 对应Student表的Name列
            comboBox1.ValueMember = "ID";     // 对应Student表的ID列
            comboBox1.SelectedIndex = -1;     // 默认不选中任何项,避免窗体加载时触发事件
        }
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        // 安全判断:未选中项或转换失败时清空ListBox并返回
        if (comboBox1.SelectedValue == null || !int.TryParse(comboBox1.SelectedValue.ToString(), out int studentId))
        {
            listBox1.Items.Clear();
            return;
        }

        listBox1.Items.Clear(); // 清空历史数据

        using (SqlConnection con = new SqlConnection(_connectionString))
        {
            using (SqlCommand cmd = new SqlCommand("spGetStudentById", con))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                // 简化参数添加,自动匹配类型
                cmd.Parameters.AddWithValue("@Id", studentId);

                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        string studentInfo = $"{sdr["Id"]},  {sdr["Name"]},  {sdr["Email"]},  {sdr["Mobile"]}";
                        listBox1.Items.Add(studentInfo);
                    }
                }
            }
        }
    }
}

额外说明

  • 将全局SqlConnection改为局部使用,配合using语句彻底避免连接泄漏;
  • FillComboBox仅查询绑定必需的列,减少数据传输量;
  • 用int.TryParse替代强制转换,避免类型转换异常;
  • 默认设置SelectedIndex = -1,防止窗体初始化时自动触发查询逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 13:35:26