views:

292

answers:

3

is there a more simple way to get combobox (WinForms) selected items text?

string result = comboBox1.Items[comboBox1.Selectedindex];

And in WPF's ComboBox?

+1  A: 

nope, sorry. That's it.

Just for interest, what part of it to you thiink is not simple?

Mawg
Something like this:string result = comboBox1.SelectedText;But it not works correct
Evl-ntnt
but that would require data duplication, which is A Bad Thing. That so to say, that the compiler would have to generate code to either maintain a separate string for current string, and copy the relevant string into it when `Selectedindex changes, or (more likely), do it with pointers, rather than copying a string. But, either way, the system is effectively now responsible for maintaining two copies of a single datum. And we all know where that can lead ...
Mawg
+1  A: 

What about

string result = (string)comboBox1.SelectedItem

Is that more simple?

Zenuka
Thanks. I just thought that has consistently failed to properly write it
Evl-ntnt
A: 

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.

Antonio Nakic Alfirevic