Silverlight - how to get the text of a selected item in combobox

Easy for you all ...

I'm new to Silverlight and really am losing things like DataTables and all. What I am also currently struggling with is how to get the text of my selected combobox element. In winforms, I would do:

ComboBox myCombo = new ComboBox....... string selected = myCombo.Text; 

I am afraid how to get this information.

+6
silverlight combobox
source share
7 answers

The selected item in your combo box is any type of item that is currently located. Therefore, if you bind to a set of strings, then the selected item will be a string:

 string mySelectedValue = ((string)MyComboBox.SelectedItem); 

If this is a more complex object, you will need to use and use the expected object. If you have XAML using a list item class, for example:

 <ComboBox x:Name="MyComboBox"> <ComboBox.Items> <ComboBoxItem> <TextBlock Text="Hello World"/> </ComboBoxItem> </ComboBox.Items> </ComboBox> 

You will then access the selected item as follows:

 string mySelectedValue = ((TextBlock)((ComboBoxItem)MyComboBox.SelectedItem).Content).Text; 
+9
source share

Right, the answer is to use myCombo.SelectionBoxItem.ToString()

+7
source share

For a complex object, use reflection with the DisplayMemberPath property:

 var itemType = cbx.SelectedItem.GetType(); var pi = itemType.GetProperty(cbx.DisplayMemberPath); var stringValue = pi.GetValue(cbx.SelectedItem, null).ToString(); 
+3
source share
 ((ComboBoxItem)comboBox1.SelectedItem).Content.ToString() 

I processed this expression.

+2
source share
 string txt=(comboboxID.SelectedItem as BindingClass).Text.ToString(); string value=(comboboxID.SelectedItem as BindingClass).Value.ToString(); public class BindingClass { public string Text { set; get; } public string Value { set; get; } } 
+1
source share

If you have a simple combobox for an array of strings, you can get the selected row using

 (string)e.AddedItems[0]; 

Suppose I have a list of products and I want to know the selected product name. Therefore, in the SelectionChanged event, I write the following code:

 private void productCombo_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { string product_type=(string)e.AddedItems[0]; } 
0
source share
 myCombo.SelectedItem.Content 

will return the contents of a ComboBoxItem. It could be TextBlock, etc. Depending on what you have and what you use for the element template.

-one
source share

All Articles