kolurbo
kolurbo

Reputation: 538

Get selected item from combobox WPF

How can I get selected value from combobox in c#?

I tried somthing like this:

XAML

<ComboBox x:Name="comboBox" SelectionChanged="comboBox_SelectionChanged_1" >
                <ComboBoxItem Name="Brno" IsSelected="True" Content="Brno"/>
                <ComboBoxItem Name="Item2" Content="Item2"/>
                <ComboBoxItem Name="Item3" Content="Item3"/>
</ComboBox>

C#

private void comboBox_SelectionChanged_1(object sender, 
    System.Windows.Controls.SelectionChangedEventArgs e)

    {
        MessageBox.Show(comboBox.SelectedValue.ToString());

    }

Message box shows me this System.Windows.Controls.ComboboxItem: Item2

I need only to show Item2

How can I do this?

Thanks

Upvotes: 2

Views: 11073

Answers (1)

haindl
haindl

Reputation: 3231

You need to get the ComboBoxItem from the SelectedItem and cast the Content (in your case) to a string:

private void comboBox_SelectionChanged_1(object sender,
    System.Windows.Controls.SelectionChangedEventArgs e)
{
    string content = ((ComboBoxItem)comboBox.SelectedItem).Content as string;
    if (content != null)
        MessageBox.Show(content);
}

Upvotes: 3

Related Questions