I have written a .Net 4.0 Winforms Numeric Editor control (which inherits from TextBox), and I have added a Value property that is a nullable decimal type, as follows:
Public Class NumericEditor
Inherits TextBox
Private _value As Decimal? = Nothing
<DefaultValue(GetType(Decimal?), "Nothing"), Bindable(True)>
Public Property Value() As Decimal?
Get
Return _value
End Get
Set(ByVal newvalue As Decimal?)
_value = newvalue
End Set
End Property
End Class
I am binding a DataTable field to an instance of the control as follows:
Dim bindingNew As New Binding("Value", _bindingSource, strFieldName, True, DataSourceUpdateMode.OnValidation, Nothing)
NumericEditor1.DataBindings.Add(bindingNew)
(I’ve created a variable for the binding object to aid in debugging, but the CLR exception is thrown on the second line.)
When databinding a field of type Int32 containing a valid value to the Value property, I’m getting a FormatException raised:
System.FormatException occurred
Message=Input string was not in a correct format.
Source=mscorlib
StackTrace:
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
InnerException:
Likewise, when databinding a field of type Int32 that contains a DBNull, I’m getting a general Exception raised:
System.Exception occurred
Message=Nothing is not a valid value for Decimal.
Source=System
StackTrace:
at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
InnerException: System.FormatException
Message=Input string was not in a correct format.
Source=mscorlib
StackTrace:
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt)
at System.ComponentModel.DecimalConverter.FromString(String value, NumberFormatInfo formatInfo)
at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
InnerException:
At this point, I’m at a loss for how to get around this exception, particularly when I’m databinding a number field to a number property, and there should be no string conversion happening. Any ideas?
(To further complicate things, I’m using a similar technique for another control where I databind a DateTime field to a nullable DateTime property, and that control works just fine.)
The string “Nothing” is the problem here. That’s a VB.NET specific keyword, only the VB.NET compiler knows what that means. The .NET framework binding code uses type converters that don’t know nothing about “Nothing”.
Just remove it because the default value for a Decimal? already is Nothing.