3
votes

How do you bind a value and a key to a listbox using Linq To Sql?

I am populating a listbox using linq to sql class, here is the WPF:

<ListBox  Name="listBox1" Loaded="listBox1_Loaded" />

And the following displays the FullNames but not the Case_Number:

using (ToolboxDataContext toolboxDB = new ToolboxDataContext())
{
    var x = toolboxDB.DropDownIndividuals().ToList(); 
    listBox1.ItemsSource = x;
}

I also tried this and did not work:

foreach (var y in x)
{
    listBox1.DisplayMemberPath = y.FullName.ToString() ;
    listBox1.SelectedValuePath = y.Case_Number.ToString() ;
    // Console.WriteLine(y.Case_Number.ToString());
}
2

2 Answers

7
votes

In the mark-up you can specify the types to bind to, such as:

<ListBox DisplayMemberPath="FullName" SelectedValuePath="Case_Number"/>
0
votes

Well,

In XAML:

<ListBox x:Name="listBox1" 
         DisplayMemberPath="FullName" 
         SelectedValuePath="Case_Number" />

In code behind:

using (ToolboxDataContext toolboxDB = new ToolboxDataContext())
     PersonsListBox.ItemsSource = toolboxDB.DropDownIndividuals().ToList();