Set SelectedItem of WPF ComboBox

Viewed 92127
<ComboBox Grid.Row="1" Grid.Column="0" Width="Auto" Name="cmbBudgetYear">
   <ComboBoxItem Content="2009" />
   <ComboBoxItem Content="2010" />
   <ComboBoxItem Content="2011" />
   <ComboBoxItem Content="2012" />
</ComboBox>

How do I set the selected item to the current year in the code behind?

Something like...

cmbBudgetYear.SelectedItem = cmbBudgetYear.Items(
                                         get the item with the Now.Year.ToString)
4 Answers

In my case I added the values manually with:

myComboBox.Items.Add("MyItem");

and then I select the wanted one with:

myComboBox.SelectedItem = "WantedItem";

instead of:

myComboBox.SelectedValue = "WantedItem";

In this case, you should be able to simply use .Text() to set it:

cmbBudgetYear.Text = "2010";

For getting the value after a change, though, and maybe it's because I didn't set SelectedValuePath="Content" everywhere, or maybe because I didn't use SelectedValue to set it (and why I'm mentioning it), it becomes slightly more complicated to determine the actual value, as you have to do this after adding the event handler for SelectionChanged in the XAML:

private void cmbBudgetYear_SelectionChanged(object sender, EventArgs e)
{
    ComboBox cbx = (ComboBox)sender;
    string yourValue = String.Empty;
    if (cbx.SelectedValue == null)
        yourValue = cbx.SelectionBoxItem.ToString();
    else
       yourValue = cboParser(cbx.SelectedValue.ToString());
}

Where a parser is needed because .SelectedValue.ToString() will give you something like System.Windows.Controls.Control: 2010, so you have to parse it out to get the value:

private static string cboParser(string controlString)
{
   if (controlString.Contains(':'))
   {
       controlString = controlString.Split(':')[1].TrimStart(' ');
   }
   return controlString;
}

At least, this is what I ran into.... I know this question was about setting the box, but can't address only setting without talking about how to get it, later, too, as how you set it will determine how you get it if it is changed.

It works fine for me.

ObservableCollection<OrganizationView> Organizations { get; set; }

Organizations = GetOrganizations();

await Dispatcher.BeginInvoke((Action)(() =>
    {
    var allOrganizationItem = new OrganizationView() { ID = 0, IsEnabled = true, Name = "(All)" }; // It is a class
    Organizations.Add(allOrganizationItem);
    cbOrganizations.DisplayMemberPath = "Name";
    cbOrganizations.SelectedValuePath = "ID";
    cbOrganizations.ItemsSource = null;
    cbOrganizations.ItemsSource = Organizations; // Set data source which has all items
    cbOrganizations.SelectedItem = allOrganizationItem; // It will make it as a selected item
    }));   
Related