GridView 自動編號欄位 - TBSerialNumberField
摘要
在「GridView 加入自動編號欄位」一文有提到如何在 GridView 中利用 TemplateField 來加入自動編號;本文將改用另一種方式,利用繼承 DataControlField 來撰寫自動編號欄位,若 GridView 需要自動編號欄位時只需加入欄位即可。
TBSerialNumberField 欄位
繼承 DataControlField 命名為 TBSerialNumberField,覆寫 InitializeCell 方法,判斷 CellType = DataControlCellType.DataCell 時就執行 InitializeDataCell 方法來產生自動編號。
Imports System.Web.UI.WebControls
Namespace WebControls
Public Class TBSerialNumberField
Inherits DataControlField
Private FRowIndex As Integer = 0
Protected Overrides Function CreateField() As System.Web.UI.WebControls.DataControlField
Return New TBSerialNumberField()
End Function
''' <summary>
''' 儲存格初始化。
''' </summary>
''' <param name="Cell">要初始化的儲存格。</param>
''' <param name="CellType">儲存格類型。</param>
''' <param name="RowState">資料列狀態。</param>
''' <param name="RowIndex">資料列之以零起始的索引。</param>
Public Overrides Sub InitializeCell(ByVal Cell As DataControlFieldCell, ByVal CellType As DataControlCellType, _
ByVal RowState As DataControlRowState, ByVal RowIndex As Integer)
FRowIndex = RowIndex
MyBase.InitializeCell(Cell, CellType, RowState, RowIndex)
If (CellType = DataControlCellType.DataCell) Then
Me.InitializeDataCell(Cell, RowState)
End If
End Sub
''' <summary>
''' 資料儲存格初始化。
''' </summary>
''' <param name="Cell">要初始化的儲存格。</param>
''' <param name="RowState">資料列狀態。</param>
Protected Overridable Sub InitializeDataCell(ByVal Cell As DataControlFieldCell, ByVal RowState As DataControlRowState)
Dim iDataRowIndex As Integer
iDataRowIndex = GetDataRowIndex()
Cell.Text = (iDataRowIndex + 1).ToString
End Sub
''' <summary>
''' 取得資料列索引。
''' </summary>
Private Function GetDataRowIndex() As Integer
Dim oGridView As GridView
If TypeOf Me.Control Is GridView Then
oGridView = DirectCast(Me.Control, GridView)
If oGridView.AllowPaging Then
Return oGridView.PageIndex * oGridView.PageSize + FRowIndex
Else
Return FRowIndex
End If
Else
Return FRowIndex
End If
End Function
End Class
End Namespace
測試程式
當 GridView 需要有自動編號欄位時,只有加入 TBSerialNumberField 即可。
<Columns>
<bee:TBSerialNumberField HeaderText="No"></bee:TBSerialNumberField>
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" InsertVisible="False"
ReadOnly="True" SortExpression="EmployeeID" />
</Columns>
執行結果如下