2012-07-31 43 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; 
相关问题