c# - 从数据表中填充行后,将行添加到 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 不属于表”。
我不明白为什么这不起作用。当我谷歌这个问题时,我看到了很多类似的解决方案。
解决方案
不是原始问题的答案,但通过以下方法,您将消除主要问题。
对于组合框的数据源,您不需要繁重的 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;
推荐阅读
- html - 如何在与 css 中的图像相同大小的图像上获得线性渐变?
- arrays - 第 K 个最大和连续子数组
- recursion - 针对 x86_64 的 Lisp 编译器的递归函数定义
- c# - 反序列化 JSON C#
- python - 如何使用列表列表作为 Python 中函数的参数
- kubernetes - 如何配置类型为 ClusterIP 且没有会话亲缘关系的 OpenShift 集群?
- postman - 在邮递员跑步者中循环我的数据文件,我可以安排跑步者本身的个人请求吗?
- python - discord.py - 将字符串转换为成员,然后将成员移动到特定频道
- generics - 由于泛型类型参数,无法将特征制成对象
- java - Filewriter 不会将所有数字写入我的文件