3

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"?

Simon P Stevens
  • 27,303
  • 5
  • 81
  • 107
Warpin
  • 6,971
  • 12
  • 51
  • 77

2 Answers2

4

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.

Scott
  • 11,840
  • 6
  • 47
  • 54
  • shouldn't it be: string tmp = (cbFileSize.SelectedItem as ComboBoxItem).Content.ToString(); ?? – spong Apr 06 '10 at 17:59
  • I edited my post to include the assumption I am making. Either SelectedItem or SelectedValue will work given that assumption. – Scott Apr 06 '10 at 18:00
0

Can also simply use the Tag method/property of the comboboxitem

<ComboBoxItem Content="This Value" Tag="This Value"/>

Then in code behind:

GetValue=ComboBoxName.SelectedItem.Tag.ToString()

Get Value will be "This Value" instead of "System.Windows.Controls.ComboBoxItem: This Value"

MattE
  • 1,044
  • 1
  • 14
  • 34