作法大致如下:
1.新增一個 Class,並繼承 CheckBoxField ,命名為 TBCheckBoxField。
2.覆寫 OnDataBindField 方法,處理繫結的欄位值。
3.在 *.aspx 檔案中,直接使用 TBCheckBoxField 來取代 CheckBoxField 即可。
<cc1:TBCheckBoxField DataField="Sex" HeaderText="性別" />
BCheckBoxField 的程式碼如下
1 Imports System.ComponentModel
2 Imports System.Web
3 Imports System.Web.UI
4 Imports System.Web.UI.WebControls
5
6 < _
7 Description("核取方塊欄位") _
8 > _
9 Public Class TBCheckBoxField
10 Inherits CheckBoxField
11
12 ''' <summary>
13 ''' 將欄位的值繫結至 TBCheckBoxField 物件中的核取方塊。
14 ''' </summary>
15 ''' <param name="sender">作用的控制項。</param>
16 ''' <param name="e">事件引數。</param>
17 Protected Overrides Sub OnDataBindField(ByVal sender As Object, ByVal e As EventArgs)
18 Dim oControl As Control = DirectCast(sender, Control)
19 Dim oNamingContainer As Control = oControl.NamingContainer
20 Dim oFieldValue As Object = Me.GetValue(oNamingContainer)
21
22 If Not TypeOf oControl Is CheckBox Then
23 Throw New HttpException("繫結的控制項非核取方塊")
24 End If
25
26 If IsDBNull(oFieldValue) Then
27 DirectCast(oControl, CheckBox).Checked = False
28 ElseIf TypeOf oFieldValue Is Boolean Then
29 DirectCast(oControl, CheckBox).Checked = CBool(oFieldValue)
30 Else
31 Try
32 DirectCast(oControl, CheckBox).Checked = CBool(oFieldValue.ToString)
33 Catch exception As FormatException
34 Throw New HttpException("無法將值轉為布林值", exception)
35 End Try
36 End If
37 DirectCast(oControl, CheckBox).Text = Me.Text
38 End Sub
39
40 End Class
2 Imports System.Web
3 Imports System.Web.UI
4 Imports System.Web.UI.WebControls
5
6 < _
7 Description("核取方塊欄位") _
8 > _
9 Public Class TBCheckBoxField
10 Inherits CheckBoxField
11
12 ''' <summary>
13 ''' 將欄位的值繫結至 TBCheckBoxField 物件中的核取方塊。
14 ''' </summary>
15 ''' <param name="sender">作用的控制項。</param>
16 ''' <param name="e">事件引數。</param>
17 Protected Overrides Sub OnDataBindField(ByVal sender As Object, ByVal e As EventArgs)
18 Dim oControl As Control = DirectCast(sender, Control)
19 Dim oNamingContainer As Control = oControl.NamingContainer
20 Dim oFieldValue As Object = Me.GetValue(oNamingContainer)
21
22 If Not TypeOf oControl Is CheckBox Then
23 Throw New HttpException("繫結的控制項非核取方塊")
24 End If
25
26 If IsDBNull(oFieldValue) Then
27 DirectCast(oControl, CheckBox).Checked = False
28 ElseIf TypeOf oFieldValue Is Boolean Then
29 DirectCast(oControl, CheckBox).Checked = CBool(oFieldValue)
30 Else
31 Try
32 DirectCast(oControl, CheckBox).Checked = CBool(oFieldValue.ToString)
33 Catch exception As FormatException
34 Throw New HttpException("無法將值轉為布林值", exception)
35 End Try
36 End If
37 DirectCast(oControl, CheckBox).Text = Me.Text
38 End Sub
39
40 End Class