2

我编写了一个 .Net 4.0 Winforms Numeric Editor 控件(继承自 TextBox),并添加了一个可为空的十进制类型的 Value 属性,如下所示:

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

我将 DataTable 字段绑定到控件的实例,如下所示:

Dim bindingNew As New Binding("Value", _bindingSource, strFieldName, True, DataSourceUpdateMode.OnValidation, Nothing)
NumericEditor1.DataBindings.Add(bindingNew)

(我为绑定对象创建了一个变量来帮助调试,但是在第二行抛出了 CLR 异常。)

当将包含有效值的 Int32 类型的字段数据绑定到 Value 属性时,我收到了一个 FormatException 引发:

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: 

同样,当对包含 DBNull 的 Int32 类型的字段进行数据绑定时,我会收到一个一般异常:

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: 

在这一点上,我不知道如何解决这个异常,特别是当我将数字字段数据绑定到数字属性时,不应该发生字符串转换。有任何想法吗?

(为了使事情更加复杂,我对另一个控件使用了类似的技术,在该控件中我将 DateTime 字段数据绑定到可为空的 DateTime 属性,并且该控件工作得很好。)

4

1 回答 1

3
<DefaultValue(GetType(Decimal?), "Nothing")>

字符串“Nothing”是这里的问题。这是一个 VB.NET 特定的关键字,只有 VB.NET 编译器知道这意味着什么。.NET 框架绑定代码使用对“Nothing”一无所知的类型转换器。

只需将其删除,因为 Decimal 的默认值?已经是无。

于 2012-05-28T20:58:39.063 回答