将 ComboBox 的 SelectedItem 属性与 Linq 匿名类型一起使用 [英] Using SelectedItem property of ComboBox with Linq Anonymous Type

查看:29
本文介绍了将 ComboBox 的 SelectedItem 属性与 Linq 匿名类型一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 3.5 中,使用 ComboBox 显示 LinQ 查询的结果.当 LinQ 查询返回匿名类型时,如何设置 ComboBox 的 SelectedItem 属性?

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?

我按照以下几行设置了 ComboBox 的数据源:

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.

推荐答案

如何将其转换为列表,然后从中选择正确的.由于 SelectedItem 似乎不起作用,您可能想尝试设置 SelectedValue.

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;

这篇关于将 ComboBox 的 SelectedItem 属性与 Linq 匿名类型一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆