C# – Using SelectedItem property of ComboBox with Linq Anonymous Type

anonymous-typesccomboboxdatasourcelinq

In C# 3.5 using a ComboBox to display the results of a LinQ Query. How do I set the SelectedItem property of the ComboBox when the LinQ query is returning an anonymous type?

I set the DataSource of the ComboBox along these lines:

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

If I do that I can choose 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 fill a ComboBox with an anonymous type result like:

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

The anonymous type I'm actually using is more complicated then that but it suffices for explanation.

Best Answer

How about converting it to a list, then choosing the correct one from it. Since SelectedItem doesn't seem to work, you may want to 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;