How to add items to Combobox from Entity Framework?

c# combobox entity-framework

Question

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
4
7/31/2012 5:26:17 PM

Accepted Answer

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

7
7/31/2012 5:34:09 PM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow