Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest way to get the selected text of a combo box containing only text entries?

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.

like image 876
DeveloperDan Avatar asked Sep 15 '10 20:09

DeveloperDan


People also ask

How do I get the ComboBox selected value?

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.

Which method is used to get the selected item in ComboBox control?

The ComboBox class searches for the specified object by using the IndexOf method.

How do you display a value from a ComboBox in a TextBox?

Text = CMB_COURSE. SelectedValue. ToString(); When the selection changes in your ComboBox , your TextBox will display the current COURSE_ID value.


2 Answers

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() 
like image 180
Andy Avatar answered Oct 11 '22 18:10

Andy


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!

like image 44
DeveloperDan Avatar answered Oct 11 '22 17:10

DeveloperDan