How to get text value from ComboBox in WPF?

It may be something that is described in C # 101, but I could not find an easily understandable answer to this question anywhere on a Google overflow or stack. Is there a better way to return text value from combobox without using this crappy work around? I figured it out?

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 do not direct me to hard, I really just collect C # and OOP.

+6
c # wpf combobox
source share
2 answers

It looks like you have ComboBoxItems in a ComboBox, so SelectedValue returns a ComboBoxItem, and ToString therefore returns something like ComboBox SomeValue .

If this happens, you can get the content using ComboBoxItem.Content:

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

However, it is better to use the ComboBoxItems collection instead of ComboBox to set ComboBox.ItemsSource to the desired row collection:

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

Then SelectedItem will immediately get the selected row.

 string selectedItem = (string)(test_site.SelectedItem); 
+11
source share

When loading events put

 DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(ComboBox.TextProperty, typeof(ComboBox)); dpd.AddValueChanged(cmbChungChi, OnTextChanged); 

And get the text through funtion

 private void OnTextChanged(object sender, EventArgs args) { txtName.Text = cmbChungChi.Text; } 

Good luck.

+1
source share

All Articles