使用LINQ查询结果直接填充ComboBox

时间:2015-08-07 14:53:56

标签: c# wpf linq combobox

我是c#/。net / WPF的新手。

我正在尝试使用从数据库中获取的值填充组合框。

LINQ查询获取数据库中所有公司的列表,代码尝试使用此列表填充ComboBox控件。

下面的C#代码成功获得结果(我以前使用MessageBox.Show()输出它。)

我的下一步是删除该位,而是输入将填写此ComboBox的代码:

<ComboBox Name="companyComboBox"/>

c#:

    using System;
    using System.Collections;
    using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data.Linq;
using System.Data.Linq.Mapping;

namespace LeadSystem
{
    /// <summary>
    /// Interaction logic for NewLead.xaml
    /// </summary>
    public partial class NewLead : Window
    {

    public NewLead()
    {


       // Use a connection string.
        DataContext db = new DataContext("Data Source=HP\\SQLEXPRESS;Initial Catalog=LeadSystem;Integrated Security=True");

        // Get a typed table to run queries.
        Table<Company> Companies = db.GetTable<Company>();

        // Attach the log to show generated SQL.
        db.Log = Console.Out;

        // Query for all companies.
        var companyQuery = 
            from c in Companies
            select new { Name = c.CompanyName, ID = c.CompanyID };

        companyComboBox.ItemsSource = companyQuery.ToList();
        companyComboBox.DisplayMemberPath = "Name";
        companyComboBox.SelectedValuePath = "ID";
        InitializeComponent();

    }
}
}

我一直遇到的问题是:

Object reference not set to an instance of an object.

^它正在谈论companyQuery,我试图用它来填充comboBox。

我认为这必须是因为延迟执行,所以我浏览了一下网络以找到解决方案。我已经看到有几个人说要在该行代码的末尾添加ToList(),但没有任何改变。

那么,这里有人知道我做错了什么吗?

我浏览过网页(包括Stackoverflow)并没有任何帮助我修复我的事情。

此外,如果一次性问两个问题并不太讨厌......如何在我的ComboBox中设置所选值和显示的值?它是否正确,我已经拥有它的方式?

由于

2 个答案:

答案 0 :(得分:6)

尝试在initializeComponent

之后填充companyComboBox
 InitializeComponent();
    companyComboBox.ItemsSource = companyQuery.ToList();
    companyComboBox.DisplayMemberPath = "Name";
    companyComboBox.SelectedValuePath = "ID";

答案 1 :(得分:0)

在设置InitializeComponent();

之前添加itemSource