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

如何在C#中使用SQLite数据库填充组合框 显示ListViewItem:{}如何解决

问题修复方案

核心错误原因

  • 项类型不匹配:你需要填充的是组合框(ComboBox)控件,但代码中错误创建了ListViewItem对象添加到组合框的条目集合。组合框默认调用对象的ToString()方法展示内容,因此只会输出类型标识ListViewItem:{},无法显示你存储在子项中的实际数据。
  • 数据库连接冗余:外层已经实例化并打开了数据库连接,内层using块又重复创建新的连接对象,属于无效代码,还可能引发资源释放异常。

修复后代码

// 使用using包裹连接,执行结束后自动释放资源,无需手动调用Close
using (SQLiteConnection conn = new SQLiteConnection(@"Data Source=C:\Users\mwbel\OneDrive\Homework\A Level\Comp Science\NEA\NEA Program\NEA Example\bin\Debug\TechWorld.db"))
{
    conn.Open();
    SQLiteDataAdapter sda = new SQLiteDataAdapter("Select productName From Products", conn);
    DataSet dataset = new DataSet();
    sda.Fill(dataset);
    // 直接将查询到的产品名字符串添加到组合框条目即可
    foreach (DataRow row in dataset.Tables[0].Rows)
    {
        OrderProductList.Items.Add(row["productName"].ToString());
    }
}

更简洁的绑定方案

你也可以直接用数据绑定省去循环遍历的代码,性能和可读性更好:

using (SQLiteConnection conn = new SQLiteConnection(@"Data Source=C:\Users\mwbel\OneDrive\Homework\A Level\Comp Science\NEA\NEA Program\NEA Example\bin\Debug\TechWorld.db"))
{
    conn.Open();
    SQLiteDataAdapter sda = new SQLiteDataAdapter("Select productName From Products", conn);
    DataTable dt = new DataTable();
    sda.Fill(dt);
    // 指定组合框的数据源和显示字段即可完成填充
    OrderProductList.DataSource = dt;
    OrderProductList.DisplayMember = "productName";
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:09:01