摘要:GridView 的 CommandField 按鈕依欄位值設定顯示或隱藏
若 GridView 的每一列需要判斷欄位值來決定是否可編輯時,可以在 GridView 的 RowDataBound 事件中做判斷並設定按鈕的顯示或隱藏。
以下範例就判斷 IsEdit 這個欄位為 False 時,則將編輯鈕隱藏,不允許編輯該資料列。
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
Dim oRow As Data.DataRowView
Dim oButton As LinkButton
If e.Row.RowType = DataControlRowType.DataRow Then
oRow = CType(e.Row.DataItem, Data.DataRowView)
If oRow IsNot Nothing Then
'若 IsEdit 欄位值為 False 時,則將編輯鈕隱藏
If Not CBool(oRow.Item("IsEdit")) Then
'尋找編輯鈕
oButton = FindCommandFieldButton(e.Row.Cells(0), "Edit")
If oButton IsNot Nothing Then
oButton.Visible = False '將編輯鈕隱藏
End If
End If
End If
End If
End Sub
''' <summary>
''' 尋找指定 CommandName 的按鈕。
''' </summary>
Private Function FindCommandFieldButton(ByVal Cell As DataControlFieldCell, ByVal CommandName As String) As LinkButton
Dim oControl As Control
Dim oButton As LinkButton
For Each oControl In Cell.Controls
If TypeOf (oControl) Is LinkButton Then
oButton = DirectCast(oControl, LinkButton)
If CommandName.ToUpper() = oButton.CommandName.ToUpper() Then
Return oButton
End If
End If
Next
Return Nothing
End Function
Dim oRow As Data.DataRowView
Dim oButton As LinkButton
If e.Row.RowType = DataControlRowType.DataRow Then
oRow = CType(e.Row.DataItem, Data.DataRowView)
If oRow IsNot Nothing Then
'若 IsEdit 欄位值為 False 時,則將編輯鈕隱藏
If Not CBool(oRow.Item("IsEdit")) Then
'尋找編輯鈕
oButton = FindCommandFieldButton(e.Row.Cells(0), "Edit")
If oButton IsNot Nothing Then
oButton.Visible = False '將編輯鈕隱藏
End If
End If
End If
End If
End Sub
''' <summary>
''' 尋找指定 CommandName 的按鈕。
''' </summary>
Private Function FindCommandFieldButton(ByVal Cell As DataControlFieldCell, ByVal CommandName As String) As LinkButton
Dim oControl As Control
Dim oButton As LinkButton
For Each oControl In Cell.Controls
If TypeOf (oControl) Is LinkButton Then
oButton = DirectCast(oControl, LinkButton)
If CommandName.ToUpper() = oButton.CommandName.ToUpper() Then
Return oButton
End If
End If
Next
Return Nothing
End Function