Sarah Vessels
Sarah Vessels

Reputation: 31650

WPF C# - ComboBox methods return object instead of string

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.

Upvotes: 0

Views: 2851

Answers (2)

x77
x77

Reputation: 737

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.

Upvotes: 2

Iain Ward
Iain Ward

Reputation: 9936

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;

Upvotes: 3

Related Questions