我有这个代码:
private void FillCombobox()
{
using (InventoryEntities c = new InventoryEntities(Properties.Settings.Default.Connection))
{
List<Customer> usepurposes = c.Customers.ToList();
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("name");
foreach (Customer usepurpose in usepurposes)
{
dt.Rows.Add(usepurpose.id, usepurpose.name);
}
comboBox1.ValueMember = dt.Columns[0].ColumnName;
comboBox1.DisplayMember = dt.Columns[1].ColumnName;
comboBox1.DataSource = dt;
}
}
我在以下位置调用此方法:
private void frmBillIn_Load(object sender, EventArgs e)
{
FillCombobox();
}
当我运行我的应用程序时,组合框不会显示客户(项目)。
只显示Model.Customer
问题是什么??
我尝试了很多解决方案,但没有一个有效。
最佳答案
您不必混合两个世界, Entity Framework 的世界和数据集的世界。直接绑定(bind):
using (InventoryEntities c = new InventoryEntities(Properties.Settings.Default.Connection))
{
comboBox1.DataSource = c.Customers;
comboBox1.ValueMember = "id";
comboBox1.DisplayMember = "name";
}
如果这不起作用,则列名称可能不同于“名称”(也许是“名称”?)。
关于c# - 如何从 Entity Framework 向组合框添加项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11745714/