tags:

views:

72

answers:

3

I give up, how do I cast this?

class AmountIsTooHighConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        //int amount = (int)value;
        //int amount = (int)(string)value;
        //int amount = (int)(value.ToString);
        //int amount = Int32.Parse(value);
        //int amount = (int)Convert.ChangeType(value, typeof(int));
        //int amount = Convert.ToInt32(value);
        if (amount >= 35)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return null;
    }
}
+1  A: 

Both Convert.ToInt32 or Int32.Parse should work... If they don't, then the value is definitely not an int ;) Try to put a breakpoint in your converter to watch the value, it might show you why it doesn't work

Thomas Levesque
Parse won't even compile. Convert will work iff the object implements IConvertible.
Steve Haigh
You're right, Parse takes a string, not an object...
Thomas Levesque
AB Kolan
thanks, there were two problems: value was actually a string and had to use System.Convert since the method is called Convert.
Edward Tanguay
A: 

Put a breakpoint at the opening parenthesis of your Convert method. Start your application in debug mode. When the breakpoint is hit analyze the actual type of value. Do the cast. If value is string cast it to string and then parse the result to get an integer. Run the program again. It should work this time.

Darin Dimitrov
A: 

If the value is actually a string object (with a content that represents an integer value), this gives the least overhead:

int amount = Int32.Parse((string)value);

The Convert.ToInt32 should be able to handle most anything that is possible to convert to an int, like a string containing digits or any numeric type that is within the range that an int can handle.

Guffa