Property Grid Number formatting

NeatNerd picture NeatNerd · May 14, 2013 · Viewed 7k times · Source

Is it possible to format numerical properties displayed in PropertyGrid of winforms?

class MyData
{
      public int MyProp {get; set;}
}

And I want it to be displayed in the grid as 1.000.000 for example.

Are there some attributes for this?

Answer

Sergey Berezovskiy picture Sergey Berezovskiy · Oct 2, 2013

You should implement custom type converter for your integer property:

class MyData
{
    [TypeConverter(typeof(CustomNumberTypeConverter))]
    public int MyProp { get; set; }
}

PropertyGrid uses TypeConverter to convert your object type (integer in this case) to string, which it uses to display object value in the grid. During editing, the TypeConverter converts back to your object type from a string.

So, you need to use type converter which should be able to convert integer to string with thousand separators and parse such string back to integer:

public class CustomNumberTypeConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, 
                                        Type sourceType)
    {
        return sourceType == typeof(string);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, 
        CultureInfo culture, object value)
    {            
        if (value is string)
        {
            string s = (string)value;
            return Int32.Parse(s, NumberStyles.AllowThousands, culture);
        }

        return base.ConvertFrom(context, culture, value);
    }

    public override object ConvertTo(ITypeDescriptorContext context, 
        CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(string))
            return ((int)value).ToString("N0", culture);

        return base.ConvertTo(context, culture, value, destinationType);
    }
}

Result:

propertyGrid.SelectedObject = new MyData { MyProp = 12345678 };

enter image description here

I recommend you to read Getting the Most Out of the .NET Framework PropertyGrid Control MSDN article to understand how PropertyGrid works and how it can be customized.