c# - 如何从 Entity Framework 向组合框添加项目?

标签 c# entity-framework combobox

我有这个代码:

    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/

相关文章:

java - 我可以将 ComboBoxModel 转换为 int 吗?

c# - 如何避免重复订阅事件?

c# - 寻找用 C# 重写的 Nibbles 游戏

c# - 如何在 .Net Core 2.2 中正确使用 ConfigurationManager.GetSection()

entity-framework - ASP.NET 核心 : NullReferenceException on getting foreign key

c# - Authorize 和 GetRoles 在 ASP.NET Identity 中不起作用

c# - 如何将数据表中的值获取到组合框?

c# - 动态确定 Structuremap 依赖关系

c# Entity Framework 选择派生子项

javafx 组合框下拉菜单从屏幕边缘消失