I have a WPF ComboBox named cbFileSize. I try to get is selected value like so:
string tmp = cbFileSize.SelectedValue.ToString();
MessageBox.Show(tmp);
But tmp gets set to "System.Windows.Control.ComboBoxItem: 16".
Which function should I use to just get the value "16"?
string tmp = (cbFileSize.SelectedValue as ComboBoxItem).Content.ToString();
or
string tmp = (cbFileSize.SelectedItem as ComboBoxItem).Content.ToString();
Edit (for more info): If you later bind your list of combo box values to a collection of strings, you would be able to do it the way you are. However, you are placing a collection of ComboBoxItems in your ComboBox, so you selectedItem or selectedValue will be a ComboBox Item:
<ComboBox x:Name="comboBox">
<ComboBoxItem>15</ComboBoxItem>
<ComboBoxItem>16</ComboBoxItem>
<ComboBoxItem>17</ComboBoxItem>
</ComboBox>
I assume you are doing something like the above. Since you're getting a ComboBoxItem as your selected item, you simply need to cast it and then get the content (which are your numeric values).
Again, the proposed solution will work for the above setup, however, maybe in the future you will bind your values to the type you want (strings or ints) insted of manually placing ComboBox items inside your ComboBox.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With