2012-07-31 37 views
3

我有這樣的代碼:如何從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

問題是什麼?

我嘗試了很多解決方案,但他們都不工作。

回答

5

您不必混淆兩個世界,實體框架的世界和DataSets的世界。直接綁定:

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

如果這不起作用,則列名可能是從「名」(「名稱」也許?)不同。

+0

我想你的代碼,但我仍然得到同樣的結果,我還試圖用「名」也是同樣的結果「Model.Customer」 – Saleh 2012-07-31 18:10:33

+0

你能後的類「模式的代碼。顧客」? – 2012-07-31 19:02:53

+0

我找到了解決方案,OMG,我覺得我很愚蠢,這是愚蠢的錯誤,無論如何非常感謝你。 – Saleh 2012-07-31 19:49:50

3

如果您使用「using」,則需要在關閉連接之前放置ToList()以進行評估。 使用的ItemsSource,ValueMember和DisplayMember是區分大小寫的

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

希望這有助於。

+0

這幫助我,因爲datasource,valuemember和displaymember沒有顯示我的代碼,但itemsource,valuememberpath ...顯示得很好。謝謝。 – Sizons 2015-11-05 07:59:01

0

請參閱下面的示例。 (名稱引用=> DAL =數據訪問層,projectEntities =實體集名稱) 希望這會有所幫助..

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; 
相關問題