如何使用 SQLite 数据库在 C# 中填充组合框?

How to populate a combo box in C# using an SQLite database?

我目前正在尝试从 SQLite 数据库添加数据,这就是我所在的位置。组合框中的数据值数量是正确的,但它没有显示实际数据值,只是 ListViewItem: {},请有人告诉我我哪里出错了。

SQLiteConnection techWorldConnection = new SQLiteConnection(@"Data Source=C:\Users\mwbel\OneDrive\Homework\A Level\Comp Science\NEA\NEA Program\NEA Example\bin\Debug\TechWorld.db"); // directs code to location of my database file
techWorldConnection.Open(); // goes to my database file and reads it

using (SQLiteConnection conn = new SQLiteConnection(techWorldConnection))
{
    SQLiteDataAdapter sda = new SQLiteDataAdapter("Select productName From Products", conn);
    DataSet dataset = new DataSet();
    sda.Fill(dataset);
    foreach (DataRow row in dataset.Tables[0].Rows)
    {
        ListViewItem lvi = new ListViewItem();
        lvi.SubItems.Add(row["productName"].ToString());
        OrderProductList.Items.Add(lvi);
    }
}
techWorldConnection.Close();

The amount of data values in the combo box is correct, but it is not showing the actual data value, just ListViewItem: {}

问题是您如何添加项目,特别是这个区域:

foreach (DataRow row in dataset.Tables[0].Rows)
{
   ListViewItem lvi = new ListViewItem();
   lvi.SubItems.Add(row["productName"].ToString());
   OrderProductList.Items.Add(lvi);
}

你不需要循环集合来获取你需要的数据,你可以填充一个DataTable,在ComboBox上设置DisplayMember,最后设置DataSourceComboBox 到您的数据表。

OrderProductList.DisplayMember = "productName";
SQLiteDataAdapter sda = new SQLiteDataAdapter("Select productName From Products", conn);
DataTable table = new DataTable();
sda.Fill(table);
OrderProductList.DataSource = table;