首页 > 解决方案 > 从数据表中填充行后,将行添加到 WinForms 组合框

问题描述

我正在使用以下代码从数据表中填充一个组合框:

public void PopulateCategoryCbo()
{
    string connString = string.Format(<connectionString>);
    NpgsqlConnection conn = new NpgsqlConnection(connString);
    conn.Open();

    string query = "SELECT id, category FROM categories ORDER BY category";
    NpgsqlCommand cmd = new NpgsqlCommand(query, conn);

    NpgsqlDataReader reader;
    reader = cmd.ExecuteReader();

    DataTable dt = new DataTable();
    //DataRow row = dt.NewRow();
    //row["id"] = 0;
    //row["category"] = "All Categories";
    //dt.Rows.InsertAt(row, 0);

    dt.Columns.Add("id", typeof(string));
    dt.Columns.Add("category", typeof(string));
    dt.Load(reader);

    cboSelectCategory.ValueMember = "id";
    cboSelectCategory.DisplayMember = "category";
    cboSelectCategory.DataSource = dt;

    conn.Close();
}

四个注释行是我尝试在数据表的顶部添加索引为 0 的“所有类别”行。我按照这个 SO question and answer做了那个代码。

row["id"] = 0;但是,当我运行该解决方案时,它会在消息“列“id”不属于表的行处中断。”

我尝试使用 0 和 1,以为它们会引用列的索引值,但我收到消息“列 0 不属于表”。

我不明白为什么这不起作用。当我谷歌这个问题时,我看到了很多类似的解决方案。

标签: c#winformsdatatablecomboboxdatarow

解决方案


不是原始问题的答案,但通过以下方法,您将消除主要问题。

对于组合框的数据源,您不需要繁重的 DataTable,而是使用普通的 c# 对象

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}

然后将数据库中的数据加载到Category对象列表中

private List<Category> LoadCategories()
{
    var query = "SELECT id, category FROM categories ORDER BY category";
    using (var connection = new NpgsqlConnection(connString))
    using (var command = new NpgsqlCommand(query, connection))
    {
        conn.Open();
        var categories = new List<Category>();
        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                var category = new Category()
                {
                    Id = reader.GetInt32(0),
                    Name = reader.GetString(1)
                }
                categories.Add(category);
            }
        }

        return categories;
    }
}

然后使用变得非常简单

var categories = LoadCategories();

var all = new Category { Id = 0, Name = "All Categories" };
categories.Insert(0, all);

cboSelectCategory.ValueMember = "Id";
cboSelectCategory.DisplayMember = "Name";
cboSelectCategory.DataSource = categories;

推荐阅读