Set Combobox SelectedValue from Code Behind In WPF

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sanndeb
    New Member
    • May 2010
    • 33

    Set Combobox SelectedValue from Code Behind In WPF

    I have a combobox like
    Code:
    <ComboBox Height="23" HorizontalAlignment="Left" Margin="88,13,0,0" Name="cmbYears" VerticalAlignment="Top" Width="112" SelectionChanged="cmbYears_SelectionChanged" Canvas.Left="13" Canvas.Top="0">
        <ComboBox.Items>
    	<ComboBoxItem Tag="2010" Content="2010" />
    	<ComboBoxItem Tag="2011" Content="2011" />
    	<ComboBoxItem Tag="2012" Content="2012" />
    	<ComboBoxItem Tag="2013" Content="2013" />
    	<ComboBoxItem Tag="2014" Content="2014" />
    	<ComboBoxItem Tag="2015" Content="2015" />
    	<ComboBoxItem Tag="2016" Content="2016" />
    	<ComboBoxItem Tag="2017" Content="2017" />
    	<ComboBoxItem Tag="2018" Content="2018" />
    	<ComboBoxItem Tag="2019" Content="2019" />
    	<ComboBoxItem Tag="2020" Content="2020" />
        </ComboBox.Items>
    </ComboBox>
    Now say after a button click i want to change the value of the combobox to current year + 1, like
    Code:
    cmbYears.SelectedValue = (DateTime.Today.Year + 1).ToString() // [B]But Its Not Working[/B]
    
    cmbYears.SelectedItem = (DateTime.Today.Year + 1).ToString() // [B]And Its also Not Working[/B]
    The code runs proprtly without error, but it doesn't reflect on the screen... nothing got selected in the combobox and accordingly OnSelectionChan ged event don't fire for the combobox :(
    So how can i set the value?
    Please Help :) Thanks...
  • sanndeb
    New Member
    • May 2010
    • 33

    #2
    Ok I Got It Done...

    Code:
    foreach (var cmbi in
                    cmbYears.Items.Cast<ComboBoxItem>().Where(cmbi => (string) cmbi.Tag == Datetime.Today.AddYears(1).Year.ToString()))
                    cmbi.IsSelected = true;
    or by
    Code:
    cmbYears.Items.Cast<ComboBoxItem>().Where(cmbi => (string) cmbi.Tag == Datetime.Today.AddYears(1).Year.ToString()).Select(a => a).Single().IsSelected = true;

    Comment

    Working...