windowsforms-2149-common-features-formatting-values-how-to-create-a-custom-formatter-to-represent-decimal-values-in-binary.md
This example demonstrates a way of creating a custom formatter object to display decimal values in binary, but only if the format string is supplied as “B”.
The result is shown in the image below.
// A custom formatter object.
public class BaseFormatter : IFormatProvider, ICustomFormatter {
// The GetFormat method of the IFormatProvider interface.
// This must return an object that provides formatting services for the specified type.
public object GetFormat(Type format) {
if (format == typeof (ICustomFormatter)) return this;
else return null;
}
// The Format method of the ICustomFormatter interface.
// This must format the specified value according to the specified format settings.
public string Format (string format, object arg, IFormatProvider provider) {
if (format == null) {
if (arg is IFormattable)
return ((IFormattable)arg).ToString(format, provider);
else
return arg.ToString();
}
if (format == "B")
return Convert.ToString(Convert.ToInt32(arg), 2);
else
return arg.ToString();
}
}
// ...
// Assign the custom formatter to the editor.
spinEdit1.Properties.DisplayFormat.FormatType = FormatType.Custom;
spinEdit1.Properties.DisplayFormat.FormatString = "B";
spinEdit1.Properties.DisplayFormat.Format = new BaseFormatter();
spinEdit1.Properties.IsFloatValue = false;
spinEdit1.EditValue = 10;
' A custom formatter object.
Public Class BaseFormatter : Implements IFormatProvider, ICustomFormatter
' The GetFormat method of the IFormatProvider interface.
' This must return an object that provides formatting services for the specified type.
Public Function GetFormat(ByVal format As Type) As Object _
Implements IFormatProvider.GetFormat
If format.ToString() = GetType(ICustomFormatter).ToString() Then
GetFormat = Me
Else
GetFormat = Nothing
End If
End Function
' The Format method of the ICustomFormatter interface.
' This must format the specified value according to the specified format settings.
Public Function Format(ByVal formatString As String, ByVal arg As Object, _
ByVal provider As IFormatProvider) As String Implements ICustomFormatter.Format
If (formatString = Nothing) Then
If TypeOf arg Is IFormattable Then
Format = CType(arg, IFormattable).ToString(formatString, provider)
Else
Format = arg.ToString()
End If
Exit Function
End If
If (formatString = "B") Then
Format = Convert.ToString(Convert.ToInt32(arg), 2)
Else
Format = arg.ToString()
End If
End Function
End Class
' ...
' Assign the custom formatter to the editor.
SpinEdit1.Properties.DisplayFormat.FormatType = FormatType.Custom
SpinEdit1.Properties.DisplayFormat.FormatString = "B"
SpinEdit1.Properties.DisplayFormat.Format = New BaseFormatter()
SpinEdit1.Properties.IsFloatValue = False
SpinEdit1.EditValue = 10