My WPF ComboBox contains only text entries. The user will select one. What is the simplest way to get the text of the selected ComboBoxItem? Please answer in both C# and Visual Basic. Here is my ComboBox:
<ComboBox Name="cboPickOne"> <ComboBoxItem>This</ComboBoxItem> <ComboBoxItem>should be</ComboBoxItem> <ComboBoxItem>easier!</ComboBoxItem> </ComboBox>
By the way, I know the answer but it wasn't easy to find. I thought I'd post the question to help others. REVISION: I've learned a better answer. By adding SelectedValuePath="Content" as a ComboBox attribute I no longer need the ugly casting code. See Andy's answer below.
The two primary methods to display and get the selected value of a ComboBox are using Combobox. SelectedItem and ComboBox. GetItemText properties in C#. A selected item's value can be retrieved using the SelectedValue property.
The ComboBox class searches for the specified object by using the IndexOf method.
Text = CMB_COURSE. SelectedValue. ToString(); When the selection changes in your ComboBox , your TextBox will display the current COURSE_ID value.
In your xml add SelectedValuePath="Content"
<ComboBox Name="cboPickOne" SelectedValuePath="Content" > <ComboBoxItem>This</ComboBoxItem> <ComboBoxItem>should be</ComboBoxItem> <ComboBoxItem>easier!</ComboBoxItem> </ComboBox>
This way when you use .SelectedValue.ToString()
in the C# code it will just get the string value without all the extra junk:
stringValue = cboPickOne.SelectedValue.ToString()
Just to clarify Heinzi and Jim Brissom's answers here is the code in Visual Basic:
Dim text As String = DirectCast(cboPickOne.SelectedItem, ComboBoxItem).Content.ToString()
and C#:
string text = ((ComboBoxItem)cboPickOne.SelectedItem).Content.ToString();
Thanks!
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