Reputation: 1072
is there a more simple way to get combobox (WinForms) selected items text?
string result = comboBox1.Items[comboBox1.Selectedindex];
And in WPF's ComboBox?
Upvotes: 1
Views: 1671
Reputation: 1179
@Zenuka's method works but I think the following is somewhat "more correct" (avoiding casts when possible):
String result = comboBox1.SelectedItem.ToString();
Upvotes: 2
Reputation: 2978
Regarding WPF combobox: I don't think there is a good general way of getting the text of the selected combobox item in WPF. The wpf combobox displays its items in a template, which can be anything (i.e. several labels nested inside a stackpanel, inside a button etc...). The template need not even display any text, it can for instance display an image or something completly different. That said, i don't think there is much need for accessing the text strings inside a selected item's UI in a combobox. That is just UI for the user, the program should interact with the selected object (not it's UI representation). There might be some exceptions to this, tho, but in that case, you will have to make a specific solution for the item template that you use, because there is no one-size-fits-all solution for this.
Upvotes: 1
Reputation: 3250
What about
string result = (string)comboBox1.SelectedItem
Is that more simple?
Upvotes: 2
Reputation: 40145
nope, sorry. That's it.
Just for interest, what part of it to you thiink is not simple?
Upvotes: 1