views:

446

answers:

2

Pulling my hair out. I've got a table 'Belts' with columns 'BeltID' and 'BeltColor'. I've got a Linq to SQL generated class, and am trying to populate a combobox and it's only partially working. Here's what I've got so far:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    using (DojoDataClassesDataContext conn = new DojoDataClassesDataContext())
    {
        var belts = (from b in conn.Belts
                    select b);

        cboBelt.DisplayMemberPath = "BeltColor";
        cboBelt.SelectedValuePath = "BeltID";
        cboBelt.ItemsSource = belts;
    }
}

And the xaml:

<ComboBox Margin="101,0,57,97" Name="cboBelt" DisplayMemberPath="{Binding Path = Belt.BeltColor}" SelectedValuePath="{Binding Path = Belt.BeltID}" Height="23" VerticalAlignment="Bottom" />

And of course there's the whole autogenerated Linq to SQL stuff in DojoDataClassesDataContext that I used to do the text box data binding without any problems (well, aside from it taking a while to figure it all out). At the moment, the combo box pulls up the text: TheNameOfMyProject.Belt as all the dropdown options but once selected it shows the correct belt color based on order.

+1  A: 

Assuming this function:

public IEnumerable<Belt> GetBelts()
{
 return /* the belts you want */;
}

Put this in your Window.Resources:

        <ObjectDataProvider x:Key="BeltObject"
                        MethodName="GetBelts"                                   
                        ObjectType="{x:Type database:Belts}">
        </ObjectDataProvider>

with:

<ComboBox Margin="101,0,57,97" Name="cboBelt" DisplayMemberPath="BeltColor" SelectedValuePath="BeltID" Height="23" VerticalAlignment="Bottom" ItemsSource="{Binding Source={StaticResource BeltObject}}"/>

This is the cleanest way to do it with WPF. You're probably running into issues because your DisplayMemberPath and SelectedValuePath are incorrect - these should be string values representing property names, not bindings to specific property values.

Jake
A: 
Anthony