By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,786 Members | 1,131 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,786 IT Pros & Developers. It's quick & easy.

Set Combobox SelectedValue from Code Behind In WPF

P: 33
I have a combobox like
Expand|Select|Wrap|Line Numbers
  1. <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">
  2.     <ComboBox.Items>
  3.     <ComboBoxItem Tag="2010" Content="2010" />
  4.     <ComboBoxItem Tag="2011" Content="2011" />
  5.     <ComboBoxItem Tag="2012" Content="2012" />
  6.     <ComboBoxItem Tag="2013" Content="2013" />
  7.     <ComboBoxItem Tag="2014" Content="2014" />
  8.     <ComboBoxItem Tag="2015" Content="2015" />
  9.     <ComboBoxItem Tag="2016" Content="2016" />
  10.     <ComboBoxItem Tag="2017" Content="2017" />
  11.     <ComboBoxItem Tag="2018" Content="2018" />
  12.     <ComboBoxItem Tag="2019" Content="2019" />
  13.     <ComboBoxItem Tag="2020" Content="2020" />
  14.     </ComboBox.Items>
  15. </ComboBox>
  16.  
Now say after a button click i want to change the value of the combobox to current year + 1, like
Expand|Select|Wrap|Line Numbers
  1. cmbYears.SelectedValue = (DateTime.Today.Year + 1).ToString() // But Its Not Working
  2.  
  3. cmbYears.SelectedItem = (DateTime.Today.Year + 1).ToString() // And Its also Not Working
  4.  
  5.  
The code runs proprtly without error, but it doesn't reflect on the screen... nothing got selected in the combobox and accordingly OnSelectionChanged event don't fire for the combobox :(
So how can i set the value?
Please Help :) Thanks...
Sep 6 '10 #1
Share this Question
Share on Google+
1 Reply


P: 33
Ok I Got It Done...

Expand|Select|Wrap|Line Numbers
  1. foreach (var cmbi in
  2.                 cmbYears.Items.Cast<ComboBoxItem>().Where(cmbi => (string) cmbi.Tag == Datetime.Today.AddYears(1).Year.ToString()))
  3.                 cmbi.IsSelected = true;
  4.  
or by
Expand|Select|Wrap|Line Numbers
  1. cmbYears.Items.Cast<ComboBoxItem>().Where(cmbi => (string) cmbi.Tag == Datetime.Today.AddYears(1).Year.ToString()).Select(a => a).Single().IsSelected = true;
  2.  
Sep 6 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.