Jerrin George Mathew Jerrin George Mathew - 2 months ago 10
C# Question

Not able to convert the value from Combo Box to Integer

I'm trying to get the value which is selected in a combo box in its handler so that I could do some operations based on every change of value. But i'm unable to convert the value into an integer. When I tried to convert it to a string and print it on the console, its printing as "System.Windows.Controls.ComboBoxItem: 100000" if the selected value is 100000.

Please find the XAML and handler code below.

<ComboBox x:Name="Scale" HorizontalAlignment="Left" Margin="660,15,0,0" Grid.Row="1" VerticalAlignment="Top" Width="60" Height="26" SelectionChanged="Scale_SelectionChanged">
<ComboBoxItem Content="1" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="10" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="50" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="100" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="200" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="400" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="500" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="750" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="1000" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="2000" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="4000" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="5000" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="10000" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="20000" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="40000" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="50000" HorizontalAlignment="Left" Width="60"/>
<ComboBoxItem Content="100000" HorizontalAlignment="Left" Width="60"/>
</ComboBox>


C# code

private void Scale_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Console.WriteLine(Scale.SelectedValue.ToString());
}

Answer

That's because the ComboBox is filled with a bunch of ComboBoxItem objects, and since SelectedValuePath is not specified, the SelectedValue will also be a <ComboBoxItem> object.

An easy way to fix that is to set the SelectedValuePath to the "Content" property :

<ComboBox x:Name="Scale" 
          SelectionChanged="Scale_SelectionChanged" 
          SelectedValuePath="Content" ...>

This way, the SelectedValue will point to ComboBoxItem.Content of the selected item.

Comments