ComboBox DataSource and Entity FrameWork

I add a data model object to my project called publishingCompanyEntities and add a ComboBox to my winform. but when I want to bind my authors list to my combo box, since the data source is filled with data, but cmoAuthors.Items.Count returns 0, but cmoAuthors.DataSource.Count returns 2 elements

  publishContext = new publishingCompanyEntities(); cmoAuthors.DataSource = publishContext.Authors; cmoAuthors.DisplayMember = "FirstName"; 
+4
source share
2 answers

You need to add .ToList() to the EntitiesSet of the authors.

 publishContext = new publishingCompanyEntities(); cmoAuthors.DataSource = publishContext.Authors.ToList(); cmoAuthors.DisplayMember = "FirstName"; cmoAuthors.Invalidate(); 

The reason is that EntitySet is not an actual collection. This is a query ( IQueryable ), and it seems that the ComboBox is not smart enough to detect this.

Calling ToList() materializes publishContext.Authors into objects.

For some reason, the ComboBox does not update its Items Collection, and then discovers a new DataSource. Invalidate() forces the control to redraw itself while updating the collection of elements.

+12
source

you need to provide the valuemember property. ValueMember

 cmoAuthors.DisplayMember = "FirstName"; cmoAuthors.ValueMember = "yourValueProperty"; 
+2
source

All Articles