Gridview 依條件判斷標記資料列

Gridview 依條件判斷標記資料列

若 GridView 中的資料列需判斷欄位值,針對符合條件的資料列做標記的動作;例如需要將「庫存小於30」的產品的資料列設定為紅色粗體字,以做警告提示使用。

以 Northwind 資料庫的 Products 資料表為例,若需要將 UnitsInStock 小於 30 的資料列標記為紅色粗體字,則在 GridView 的 RowDataBound 事件中撰寫如下程式碼。

在 RowDataBound 事件中處理有個好處,因為只有這時抓得到繫結的資料,可以直接利用欄位值去做判斷,不需使用 FindControl 的方式來判斷;一般我會建議非必要儘量少用 FindControl,因為 FindControl 常會因設計畫面的變更(例如 GridView 加入一個新的欄位),而導致程式碼錯誤。

    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        Dim oRow As Data.DataRowView

        If e.Row.RowType = DataControlRowType.DataRow Then
            oRow = CType(e.Row.DataItem, Data.DataRowView)
            '若 UnitsInStock 欄位值小於30,則將該資料列標記為紅色粗體字
            If CInt(oRow("UnitsInStock")) < 30 Then
                e.Row.Font.Bold = True
                e.Row.ForeColor = Drawing.Color.Red
            End If
        End If
    End Sub

執行結果如下

ASP.NET 魔法學院