Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set SelectedItem of WPF ComboBox

Tags:

combobox

wpf

<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) 
like image 357
knockando Avatar asked Aug 02 '10 19:08

knockando


2 Answers

There exist many ways to do this but for your example, I would change the ComboBox-Tag as follows:

<ComboBox Grid.Row="1" Grid.Column="0"            Name="cmbBudgetYear" SelectedValuePath="Content"> 

I added the attribute-defition SelectedValuePath="Content". After that you can set the value with a corresponding string, e.g.:

cmbBudgetYear.SelectedValue = "2009"; 

Take care that the value must be a string. For your example, use

cmbBudgetYear.SelectedValue = DateTime.Now.Year.ToString(); 

An additional idea

If you use the code-behind anyway, would it be a possibility to fill the combobox with integers. Someting like:

for(int y=DateTime.Now.Year;y>DateTime.Now.Year-10;y--){  cmbBudgetYear.Items.Add(y); } 

..then you can select the values extremly simple like

cmbBudgetYear.SelectedValue = 2009; 

... and you would have also other advantages.

like image 147
HCL Avatar answered Sep 27 '22 23:09

HCL


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"; 
like image 40
Simone Brognoli Avatar answered Sep 28 '22 00:09

Simone Brognoli