C# WPF Combobox select first item

Roboneter picture Roboneter · Dec 9, 2013 · Viewed 67.4k times · Source

Goodday,

I want my combobox to select the first item in it. I am using C# and WPF. I read the data from a DataSet. To fill the combobox:

DataTable sitesTable = clGast.SelectAll().Tables[0];
cbGastid.ItemsSource = sitesTable.DefaultView;

Combo box XAML code:

<ComboBox 
   Name="cbGastid" 
   ItemsSource="{Binding}" 
   DisplayMemberPath="Description" 
   SelectedItem="{Binding Path=id}"
   IsSynchronizedWithCurrentItem="True" />

If I try:

cbGastid.SelectedIndex = 0; 

It doesn't work.

Answer

Brian picture Brian · Dec 9, 2013

Update your XAML with this:

<ComboBox 
        Name="cbGastid" 
        ItemsSource="{Binding}" 
        DisplayMemberPath="Description" 
        SelectedItem="{Binding Path=id}"
        IsSynchronizedWithCurrentItem="True"
        SelectedIndex="0" />  // Add me!