Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
295 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...