Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i get the text value from a ComboBox in WPF?

Tags:

c#

combobox

wpf

This may be something covered in C# 101 but I haven't been able to find an easy to understand answer to this question anywhere on google or stack overflow. Is there a better way to return a text value from a combobox without using this crappy work around I came up with?

private void test_site_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string cmbvalue = "";

    cmbvalue = this.test_site.SelectedValue.ToString();
    string[] cmbvalues = cmbvalue.Split(new char[] { ' ' });

    MessageBox.Show(cmbvalues[1]);
}

Please don't rail on me to hard I'm really just now picking up c# and OOP.

like image 797
Akers Avatar asked Feb 27 '10 19:02

Akers


People also ask

How do I get selected text in ComboBox?

You can use the SelectedText property to retrieve or change the currently selected text in a ComboBox control. However, you should be aware that the selection can change automatically because of user interaction.

How do I get the ComboBox selected value?

string strID = MyCombobox2. SelectedValue. ToString();

What is Displaymemberpath?

Specifies the path into the selected item from which to get the text. The Text and DisplayText properties will return values from this path.


1 Answers

It looks like you have ComboBoxItems in your ComboBox, so that SelectedValue is returning a ComboBoxItem and ToString is therefore returning something like ComboBox SomeValue.

If that's the case, you can get the content using ComboBoxItem.Content:

ComboBoxItem selectedItem = (ComboBoxItem)(test_site.SelectedValue);
string value = (string)(selectedItem.Content);

However, a better approach is, instead of populating the ComboBox with a collection of ComboBoxItems, to set ComboBox.ItemsSource to the desired collection of strings:

test_site.ItemsSource = new string[] { "Alice", "Bob", "Carol" };

Then SelectedItem will get you the currently selected string directly.

string selectedItem = (string)(test_site.SelectedItem);
like image 154
itowlson Avatar answered Nov 04 '22 03:11

itowlson