有時 CheckBoxField 會需要繫結到非布林值的欄位,例如繫結的欄位值為 0 或 1;但是預設的 CheckBoxField 若繫結的欄位值為 0 或 1 時 (非布林值) 會發生錯誤。一般的解法都是使用 TemplateField 來處理,不過本文使用另一種方式,改寫 CheckBoxField 類別,讓 CheckBoxField 有辨法繫結 0 或 1 的欄位值。

作法大致如下:

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 ObjectByVal 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



posted on 2007-12-06 22:28  jeff377  阅读(494)  评论(0编辑  收藏  举报