/ Published in: C#
                    
                                        
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
                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
                            
                        
                        Copy this code and paste it in your HTML
// 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 ;
URL: http://koniosis.blogspot.com/2009/02/integers-as-hex-in-propertygrid-c-net.html
Comments
 Subscribe to comments
                    Subscribe to comments
                
                