views:

36

answers:

2

I'm new to WPF and I'm trying to figure out how to get the current text value of the selected item in a ComboBox. I saw in this question someone suggested doing MyComboBox.SelectedItem.Text. However, SelectedItem returns object for me, so I only have options like ToString(), Equals, etc. What's going on? I'm using .NET 3.5, developing in VS 2010. The other methods I thought might be of use, like MyComboBox.SelectedValue, also return object. SelectedIndex returns int, but I want a string value. MyComboBox is of type ComboBox. I'm accessing it in a method to handle the SelectionChanged event.

+1  A: 

Have you tried MyComboBox.Text ? That will return you the text of the currently selected item.

You can also parse the SelectItem into the type of the datasource you've set it and get the text property you want directly from the object?

ie

MyObject obj = (MyObject)MyComboBox.SelectedItem;
string text = obj.Text;
w69rdy
That definitely gives me a string value. It seems like I'm getting the value of what the ComboBox used to be, though, even when I cast the `object` given to my event handler to `ComboBox` and use its `Text` value.
Sarah Vessels
You're getting the value of what it used to be? Is the event being triggered somehow before the new item is being set?
w69rdy
I'm not sure. I have this in my XAML: ` SelectionChanged="Product_SelectionChanged"`, and `Product_SelectionChanged` is the name of my event handler method. Should I be using a different event?
Sarah Vessels
No thats the event I would use, although you could try using another to see if it still has the same problem. Does it fire twice at all or just the once when you select a different item in the combobox?
w69rdy
MyComboBox.Text gives you, quite simply the text that is displayed on top (and when closed). If your combobox allows editing it could be different from the selected item.
Henk Holterman
When stepping through my code debugging, `Text` was empty the first time when I changed the value of the ComboBox and ended up in the event handler. `productSelector.SelectedItem.ToString()` however had the new value I had just selected, so that's apparently what I need.
Sarah Vessels
This post seems to describe what I was seeing: the `Text` property showing the previously selected value. http://leeontech.wordpress.com/2008/02/26/getting-the-text-of-the-selecteditem-in-combobox/
Sarah Vessels
+1  A: 

Each Item is a Object. The Displayed Data is Object.ToString (Item.ToString)

But you can Use any other Object member, Property or method from Object. You have added the object to Combo, then you know Object Type and can Cast it.

x77