user9250176
user9250176

Reputation:

System.Reflection.TargetInvocationException in wpf combobox

Simple question, but I'm stuck a few hours so maybe you can save me couple of hours.

I have a combobox, and I want to show the user selection on MessageBox

My xaml:

<ComboBox x:Name="product_combobox" IsEditable="True" IsReadOnly="True" Text="Mail version" Height="24" Margin="155,105,155,0"  HorizontalAlignment="Center" VerticalAlignment="Top"  Width="210" SelectionChanged="comboBox_SelectionChanged">
        <ComboBoxItem IsSelected="False" Content="--Product--"/>
        <ComboBoxItem Content="Item1"/>
        <ComboBoxItem Content="Item2"/>
        <ComboBoxItem Content="Item3"/>
    </ComboBox>

code behind:

        private void comboBox_SelectionChanged(object sender , SelectionChangedEventArgs e)
        {
            ComboBoxItem selectedItem = (ComboBoxItem)(this.product_combobox.SelectedValue);               
            string text = (sender as ComboBox).SelectedItem as string;
            MessageBox.Show(text);
        }

When I run in debug I see the exeption:

System.Reflection.TargetInvocationException

, please help me to save more hours.


EDIT:

private void comboBox_SelectionChanged(object sender , SelectionChangedEventArgs e)
        {
           MessageBox.Show(product_combobox.SelectedValue.ToString());
        }

also gives same exeption

Upvotes: 1

Views: 356

Answers (1)

Tronald
Tronald

Reputation: 1585

Certain .NET Framework versions have an issue with reflection of ComboBox items if the items are set in XAML. Setting the items in the code behind will fix the issue.

  product_combobox.Items.Add("--Product--");
  product_combobox.Items.Add("Item1");
  product_combobox.Items.Add("Item2");
  product_combobox.Items.Add("Item3");

Upvotes: 1

Related Questions