I found an excellent article in the MSDN library by Règis Brid showing how to create a custom DataGridView column for NumericUpDown controls at
http://msdn2.microsoft.com/en-us/library/aa730881(vs.80).aspx (You'll have to copy and paste that link 'cause the auto-formatter stops at the close paren.) I am using the article as a basis for a numeric textbox column, but I am really puzzling over some of the code in the DataGridViewNumericUpDownCell class inherited from DataGridViewTextBoxCell.
The GetFormattedValue method looks like this:
protected override object GetFormattedValue(object value,
int rowIndex,
ref DataGridViewCellStyle cellStyle,
TypeConverter valueTypeConverter,
TypeConverter formattedValueTypeConverter,
DataGridViewDataErrorContexts context)
{
object formattedValue
= base.GetFormattedValue(value, rowIndex, ref cellStyle, valueTypeConverter,
formattedValueTypeConverter, context);
string formattedNumber = formattedValue as string;
if (!string.IsNullOrEmpty(formattedNumber) && value != null)
{
Decimal unformattedDecimal = System.Convert.ToDecimal(value);
Decimal formattedDecimal = System.Convert.ToDecimal(formattedNumber);
if (unformattedDecimal == formattedDecimal)
{
return formattedDecimal.ToString((this.ThousandsSeparator ? "N" : "F")
+ this.DecimalPlaces.ToString());
}
}
return formattedValue;
}
(I've slightly reformatted the above text to avoid superwide lines, but haven't changed the code.)
Two things bother me:
First, the call to base.GetFormattedValue followed by the check for null or empty string. According to the docs for the framework, the method returns null "if the cell does not belong to a DataGridView control". If that is the case, it seems there should be an easier way to test for that condition than formatting the value. As for the empty string, I'm not sure what that is about, but I suspect it has to do with null values.
Second, inside the "if" condition following the call to the base method, there are two Convert.ToDecimal calls and a comparison of the results. I am at pretty much a total loss to understand all that! I might guess that there is an assumption that if they agree somebody else is doing some formatting and we don't want to muck it up, but this seems like a thin hypothesis.
No other custom GridView column code I've looked at does anything like this, although a few go out of their way to get sensible default values in various cases.
I would like to avoid what appears to be a lot of overhead here because from what I've read GetFormattedValue gets called a
lot to check sizes of columns and such as well as to format display values.
Anybody have any insight on these two bits of coding?
...Jim