如何从Entity Framework将项目添加到Combobox? [英] How to add items to Combobox from Entity Framework?

查看:67
本文介绍了如何从Entity Framework将项目添加到Combobox?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

  private void FillCombobox()
{
使用(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(使用目的中的客户使用目的)
{
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();
}

当我运行我的应用程序时,组合框将不会显示客户(项目)。 / p>

仅显示 Model.Customer



出什么问题了?



我尝试了许多解决方案,但没有一个起作用。

解决方案

不必将实体框架和数据集两个世界混为一谈。直接绑定:

 使用(InventoryEntities c = new InventoryEntities(Properties.Settings.Default.Connection))
{
comboBox1.DataSource = c.Customers;
comboBox1.ValueMember = id;
comboBox1.DisplayMember =名称;
}

如果这不起作用,则列名可能与 name不同(也许是名称?)。


I have this code:

    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;

        }
    }

and I call this method in:

    private void frmBillIn_Load(object sender, EventArgs e)
    {
        FillCombobox();
    }

When I run my app, combobox will not display customers(items).

just display Model.Customer

What is the problem??

I tried many solution but non of them are working.

解决方案

You don't have to mix two worlds, the world of Entity Framework and the world of DataSets. Bind directly:

    using (InventoryEntities c = new InventoryEntities(Properties.Settings.Default.Connection))
    {
        comboBox1.DataSource    = c.Customers;
        comboBox1.ValueMember   = "id";
        comboBox1.DisplayMember = "name";
    }

If this does not work, then the column name could be different from "name" ("Name" perhaps?).

这篇关于如何从Entity Framework将项目添加到Combobox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆