Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combobox and SelectionChanged problem

Tags:

c#

combobox

wpf

I'm trying to check for a value in my combobox, but it fails, my value is never matched and I have this warning :

Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

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

Thanks.

like image 977
ojsim Avatar asked Mar 18 '26 10:03

ojsim


2 Answers

There are various ways to fix, one if to cast to a string, the other is to call ToString on the SelectedValue.

As you have stated that some of the other suggested answers do not work, are you sure the item in the Combobox is in fact a string?

For example, this will work with the fixes suggested:

<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 this won't:

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

You can quickly determine if this is the case by running the following code in your existing event handler:

   MessageBox.Show(((ComboBox)sender).SelectedValue.GetType().ToString());
like image 132
RichardOD Avatar answered Mar 19 '26 23:03

RichardOD


SelectedValue's type is object so, even it matches the value the equal operation will return false, so you have to compare string with string instead like the following:

    if (((ComboBox)sender).SelectedValue.ToString() == "Floyd-Warshall")
like image 32
Homam Avatar answered Mar 20 '26 00:03

Homam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!