Calanus
Calanus

Reputation: 26277

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

Easy one for you all...

I'm new to Silverlight and really missing stuff like DataTables and things. What I'm also currently struggling with is how to get the text of my combobox's currently selected item. In winforms I would have done:

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

I'm struggling how to get this info out.

Upvotes: 6

Views: 15616

Answers (7)

Calanus
Calanus

Reputation: 26277

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

Upvotes: 7

Mangesh
Mangesh

Reputation: 5841

((ComboBoxItem)comboBox1.SelectedItem).Content.ToString()

I got it worked by this statement.

Upvotes: 3

PhilipChrist
PhilipChrist

Reputation: 19

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;
      }
 }

Upvotes: 1

Munim
Munim

Reputation: 2768

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

(string)e.AddedItems[0];

Suppose I have a product list combo and I want to know the selected product name. So 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];
        }

Upvotes: 0

Donovan Groeneweegen
Donovan Groeneweegen

Reputation: 63

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();

Upvotes: 3

Jason Jackson
Jason Jackson

Reputation: 17260

The selected item of your combo box is whatever type of item is currently holding. So if you set the binding to a collection of strings, then the selected item will be a string:

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

If it is a more complex object you will need to cast and use the expected object. If you have XAML using the list box item class, like:

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

Then you would access the selected item like this:

string mySelectedValue = 
  ((TextBlock)((ComboBoxItem)MyComboBox.SelectedItem).Content).Text;

Upvotes: 9

Muad&#39;Dib
Muad&#39;Dib

Reputation: 29216

myCombo.SelectedItem.Content

will return the content of the ComboBoxItem. This could be a TextBlock, etc. depending on what you have in there, and what you are using for an item template.

Upvotes: -1

Related Questions