Using SelectedItem property of ComboBox with Linq Anonymous Type
10,489
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;
Author by
Ryan Roper
Updated on June 04, 2022Comments
-
Ryan Roper almost 2 years
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.
-
Ryan Roper about 15 yearsThat would only add the first result from the LinQ query to the dropdown list. I want to add all the results to the list, but select a specific item afterword.
-
JaredPar about 15 yearsI see what you're saying, give me a sec and i'll update the answer
-
Ryan Roper about 15 yearsI just tried it, it doesn't seem to change the selected item. It also only works if done right when it's loaded. The selected item may get set in another function. Thanks.
-
tvanfosson about 15 yearsDid you try setting SelectedValue to the correct ProductId instead. I'll update the code.
-
Ryan Roper about 15 yearsThat works if you know which record in the list is the one you want by record number. It doesn't work if you set the selecteditem in a different function from the one that loads the list. Thanks again.
-
tvanfosson about 15 yearsAlso, I had an error in the selection logic. I've fixed that -- should have been a Where method instead of a Select method. Changing that may make the previous example work.
-
Ryan Roper about 15 yearsActually this caused me to stumble on the answer. Apparently once you set the valuemember property to the name of the field you want in the anon type just setting the SelectedValue = 5 changes the selected item.
-
tvanfosson about 15 yearsSure. I don't know why I was thinking you had to set the name.