Combobox and SelectionChanged Problem

I am trying to check the value in my combobox, but it fails, my value is never mapped, and I have this warning:

Possible inadvertent reference comparison; to get a comparison of values, superimpose the left side on the type 'String'

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

        if (((ComboBox)sender).SelectedValue == "Floyd-Warshall")
        {
            MessageBox.Show("foobar");

Thank.

+3
source share
3 answers

There are various remedies: one, if set to a string, the other, to call ToString on SelectedValue.

As you stated that some of the suggested answers do not work, are you sure that the element in Combobox is actually a string?

For example, this will work with the proposed fixes:

<Window x:Class="ExerciseOne.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" xmlns:extern="clr-namespace:System;assembly=mscorlib">
    <Grid>
    <ComboBox SelectionChanged="ComboBox_SelectionChanged">
        <ComboBox.Items>
                <extern:String>Hello</extern:String>
                <extern:String>Floyd-Warshall</extern:String>
            </ComboBox.Items>
    </ComboBox>
    </Grid>
</Window>

But it will not be:

<Window x:Class="ExerciseOne.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" xmlns:extern="clr-namespace:System;assembly=mscorlib">
    <Grid>
    <ComboBox SelectionChanged="ComboBox_SelectionChanged">
        <ComboBox.Items>
                <ComboBoxItem>Hello</ComboBoxItem>
                <ComboBoxItem>Floyd-Warshall</ComboBoxItem>
            </ComboBox.Items>
    </ComboBox>
    </Grid>
</Window>

, , :

   MessageBox.Show(((ComboBox)sender).SelectedValue.GetType().ToString());
+2

VALUE object, , false, , :

    if (((ComboBox)sender).SelectedValue.ToString() == "Floyd-Warshall")
+2

warning for SelectedValue you should add .toString ()

0
source

All Articles