'combobox tostring() returns object instead of value
I want to retrieve the string value selected in a combo box and convert into an integer, however the SelectedItem method always returns the name of the object. Other posts suggest to use the Content property of SelectedItem but it is not available to me in vs2017 using .net 4.6.1. Can someone help me get the value without parsing the string?
Here's the Xaml followed by the cs file:
<ComboBox x:Name="Combo_BaudRate" SelectedValuePath="Content"
HorizontalAlignment="Left" VerticalAlignment="Top"
Width="120" Margin="112,81,0,0"
SelectionChanged="ComboBox_SelectionChanged"
IsReadOnly="True" >
<ComboBoxItem Content="1200" />
<ComboBoxItem Content="2400" />
<ComboBoxItem Content="4800" />
<ComboBoxItem Content="9600" />
<ComboBoxItem Content="38400" />
</ComboBox>
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Selected_Port_Baudrate = Combo_BaudRate.SelectedItem.ToString();
}
Solution 1:[1]
SelectedItem
on ComboBox
return the first selected ComboBoxItem
.
You want to get the value of a property of the selected item, not the item itself. So you should use SelectedValue
in conjunction with SelectedValuePath
to bind the property value and convert it to the appropriate type :
int selectedBaudRate = int.Parse(Combo_BaudRate.SelectedValue.ToString());
Note that the underlying type of SelectedValue
is string
because you specified the ComboBoxItem
property Content
as the SelectedValuePath
.
If you do not set both SelectedValuePath
and SelectedValue
, SelectedValue
will contain the same object as SelectedItem
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |