开发者

Combobox and SelectionChanged problem

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 le开发者_如何学编程ft hand side to type 'string'

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

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

Thanks.


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


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


the warning for the SelectedValue you have to add .toString()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜