Using the SelectedItem Property for ComboBox w / Linq Anonymous Type

In C # 3.5, using a ComboBox to display LinQ query results. How to set the selecteditem property in a combo box when a LinQ query returns an anonymous type?

I set the dropdown list data source on these lines:

comboBox1.DataSource = from p in db.products select p; comboBox1.DisplayMember = "Name"; comboBox1.ValueMember = "ProductId"; 

If I do this, I can select the selected item by doing something like:

 comboBox1.SelectedItem = (from p in db.products where p.ProductId = 5 select p).First(); 

The problem is that I want to populate combobox with an anonymous result like:

 comboBox1.DataSource = from p in db.products select new { p.ProductId, p.Name }; 

The anonymous type that I actually use is more complex than that, but this is enough to explain.

+4
source share
2 answers

How to convert it to a list, and then choose the right one from it. Since SelectedItem does not work, you can try setting SelectedValue.

 var productList = (from p in db.products select new { ProductId = p.ProductID, Name = p.Name }).ToList(); comboBox1.DataSource = productList; comboBox1.DisplayMember = "Name"; comboBox1.ValueMember = "ProductId"; comboBox1.SelectedValue = 5; 
+2
source

That should do the trick

 var list = (from p in db.products select new { p.ProductId, p.Name }).ToList(); comboBox1.DataSource = list; comboBox1.SelectedItem = list[0]; 
0
source

All Articles