/ Published in: C#
URL: http://koniosis.blogspot.com/2009/02/integers-as-hex-in-propertygrid-c-net.html
Displaying values as hex in a PropertyGrid by using a TypeConverter class. The TypeConverter class is assigned as a property to the PropertyGrid's data element.
Consider improving by making the UInt32HexTypeConverter a generic/template as in HexTypeConverter. Also, consider deriving from BaseNumberConverter .
See 'How to: Implement a Type Converter' in MSDN
Expand |
Embed | Plain Text
// Included... // [1] Define TypeConverter class for hex. // [2] use it when defining a member of a data class using attribute TypeConverter. // [3] Connect the data class to a PropertyGrid. // [1] define UInt32HexTypeConverter is-a TypeConverter public class UInt32HexTypeConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { { return true; } else { return base.CanConvertFrom(context, sourceType); } } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { { return true; } else { return base.CanConvertTo(context, destinationType); } } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { { return string.Format("0x{0:X8}", value); } else { return base.ConvertTo(context, culture, value, destinationType); } } public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { { string input = (string)value; if (input.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { input = input.Substring(2); } return UInt32.Parse(input, System.Globalization.NumberStyles.HexNumber, culture); } else { return base.ConvertFrom(context, culture, value); } } } // UInt32HexTypeConverter used by grid to display hex. // [2] define a class for data to be associated with the PropertyGrid. [DefaultPropertyAttribute("Name")] public class Data . . . public UInt32 stat; [CategoryAttribute("Main Scanner"), DescriptionAttribute("Status"), TypeConverter(typeof(UInt32HexTypeConverter))] public UInt32 Status { get { return stat; } } . . . // [3] reference data for propertyGrid. (here, myData is a Data). propertyGrid1.SelectedObject = myData ;
Comments
Subscribe to comments
You need to login to post a comment.

Hi, I think it is worth pointing out that my original post (http://koniosis.blogspot.com/2009/02/integers-as-hex-in-propertygrid-c-net.html) allows any integer property of any object displayed in the PropertyGrid to be shown in Hex without the need to add Attributes. This also allows the hex display to be toggled at runtime as required.
I'd be interested to see a variant that uses the BaseNumberConverter or derived classes.
Thanks