Wednesday, March 24, 2010

WPF Combobox Databind to a Dataset

Often there is a question on "how to bind ComboBox to a Dataset?". A short and simple answer, You cannot. The more specific answer is, you bind to a DataTable and not a DataSet.

There are two ways to accomplish this,
1. Setting the Path of the ItemsSource in XAML and then setting the DataSet as the DataContext.
XAML,
< ComboBox 
    x:Name="myComboBox"
    ItemsSource="{Binding Path=yourTableName}">               
</ComboBox>

Code behind,
DataSet ds; //ASSUMPTION: This DataSet contains a Table named yourTableName
myComboBox.DataContext = ds;


2. Setting the ItemsSource of the ComboBox to the DataTable from the DataSet.
XAML,
< ComboBox 
    x:Name="myComboBox">                
</ComboBox>

Code behind,
DataSet ds; //ASSUMPTION: This DataSet contains a Table named yourTableName
myComboBox.ItemsSource = ds["yourTableName"];