How to add items to Combobox from Entity Framework?

半城伤御伤魂 提交于 2020-01-03 16:53:48

问题


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.


回答1:


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?).




回答2:


If you use "using" you need to place a ToList() for evaluate before close connection. use ItemsSource , ValueMember and DisplayMember are case sensitive

using (InventoryEntities c = new InventoryEntities())
    {
        comboBox1.ItemsSource   = c.Customers.toList();
        comboBox1.ValueMemberPath   = "Id";
        comboBox1.DisplayMemberPath = "Name";
    }

Hope this help.




回答3:


Refer following sample. (name references => DAL=Data access layer, projectEntities = entity set name) Hope this will help..

List itemsList = new List();

            using (DAL.projectEntities en = new DAL.projectEntities())
            {
                foreach (var item in en.tableName.Where(a => a.tableName != null).ToList())
                {
                    itemsList.Add(item.tableFieldName);
                }                                   
            }

            comboboxTable.ItemsSource = itemsList;



回答4:


In the current version of WinForms I have found this to work

RentalsEntities1 db = new RentalsEntities1();
        List<SiteSeeingLocation> ssloc = db.SiteSeeingLocations.ToList();
        cbSites.DataSource = ssloc;
        cbSites.ValueMember = "id";
        cbSites.DisplayMember = "ssLocation";


来源:https://stackoverflow.com/questions/11745714/how-to-add-items-to-combobox-from-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!