Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add items to Combobox from Entity Framework?

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.

like image 214
Saleh Avatar asked Jul 31 '12 17:07

Saleh


2 Answers

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.

like image 30
Xilmiki Avatar answered Oct 19 '22 17:10

Xilmiki


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

like image 141
Wiktor Zychla Avatar answered Oct 19 '22 18:10

Wiktor Zychla