想法是这样的,想通过绑定来显示一个数据库字段的值,但是需要特殊格式化后显示这个值,因此想利用binding对象和DataGridColumn对象都有的formatString属性和formatInfo属性来进行修改,代码如下Public Class StatusFormatProvider
Implements IFormatProvider, ICustomFormatter#Region "IFormatProvider Members"
Public Function GetFormat(ByVal formatType As Type) As Object Implements IFormatProvider.GetFormat
If formatType Is GetType(ICustomFormatter) Then
Return Me
Else
Return Nothing
End If
End Function
#End Region#Region "ICustomFormatter Members"
Public Function Format(ByVal formatString As String, ByVal arg As Object, ByVal formatProvider As IFormatProvider) As String Implements ICustomFormatter.Format
If Not formatProvider.Equals(Me) Then Return Nothing
If Not formatString.Equals("S") Then Return Nothing Return [Enum].GetName(GetType(Status), arg)
End Function
#End RegionEnd ClassBinding对象调用
Dim binding As New System.Windows.Forms.Binding("Text", Me.dataSet, "Table1.Status", True, DataSourceUpdateMode.Never, Nothing, "{0:S}", New StatusFormatProvider)
Me.txtStatus.DataBindings.Add(binding)DataGridColumn对象调用
Me.dgrCol_Status.Format = "{0:S}"
Me.dgrCol_Status.FormatInfo = New StatusFormatProvider很可惜,均无法生效,但使用String.Format(new StatusFormatProvider, "{0:S}", 1)是可以的
请大家看看哪里有问题
IFormatProvider
Implements IFormatProvider, ICustomFormatter#Region "IFormatProvider Members"
Public Function GetFormat(ByVal formatType As Type) As Object Implements IFormatProvider.GetFormat
If formatType Is GetType(ICustomFormatter) Then
Return Me
Else
Return Nothing
End If
End Function
#End Region#Region "ICustomFormatter Members"
Public Function Format(ByVal formatString As String, ByVal arg As Object, ByVal formatProvider As IFormatProvider) As String Implements ICustomFormatter.Format
If Not formatProvider.Equals(Me) Then Return Nothing
If Not formatString.Equals("S") Then Return Nothing Return [Enum].GetName(GetType(Status), arg)
End Function
#End RegionEnd ClassBinding对象调用
Dim binding As New System.Windows.Forms.Binding("Text", Me.dataSet, "Table1.Status", True, DataSourceUpdateMode.Never, Nothing, "{0:S}", New StatusFormatProvider)
Me.txtStatus.DataBindings.Add(binding)DataGridColumn对象调用
Me.dgrCol_Status.Format = "{0:S}"
Me.dgrCol_Status.FormatInfo = New StatusFormatProvider很可惜,均无法生效,但使用String.Format(new StatusFormatProvider, "{0:S}", 1)是可以的
请大家看看哪里有问题
IFormatProvider
this.textBox1.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bindingSource1, "Id", true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, "Empty", "0000000"));
“Empty”是Id为 Null时,显示的字符串。
“0000000”是对Id(数字)的格式化。不够位数左边补0.例如1就显示0000001
不行的,我试过了,debug进去,连StatusFormatProvider的GetFormat接口都不会调用
不清楚为何