Fill ComboBox with LINQ Query Results Directly

I am new to C # /. net / WPF.

I am trying to populate a combobox with values ​​taken from a database.

The LINQ query receives a list of all the companies in the database, and the code attempts to populate the ComboBox control with this list.

The C # code below successfully gets the results (I previously output it using MessageBox.Show ()).

My next step was to remove this bit and instead enter the code that this ComboBox will populate:

<ComboBox Name="companyComboBox"/> 

FROM#:

  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(); } } } 

The problem I keep getting:

 Object reference not set to an instance of an object. 

^ he talks about companyQuery where I am trying to use it to populate a comboBox.

I thought it should be due to delayed execution, and so I found around the Internet to find a solution. I saw several people say add ToList () at the end of this line of code, but nothing has changed.

So, does anyone here know what I'm doing wrong?

I browsed the web (including Stackoverflow) and nothing helped me fix mine.

Also, if it’s not too cheeky to ask two questions at a time ... How do I set the selected value and display values ​​in my ComboBox? Is this right, as I already have?

thanks

+4
source share
2 answers

Try filling out the ComboBox after initializing Component

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

Put InitializeComponent(); before setting itemSource

0
source

All Articles