【问题标题】:How to change gridview cell background color based on its value如何根据其值更改gridview单元格背景颜色
【发布时间】:2015-08-22 05:29:58
【问题描述】:

我需要更改 gridview 单元格的背景颜色,但它不起作用。

Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView2.RowDataBound
    If e.Row.RowType = DataControlRowType.DataRow Then
        For Each er As GridViewRow In GridView2.Rows
            If er.Cells(4).Text = "Formation" Then
                er.Cells(4).BackColor = Color.Red
            End If
        Next
    End If
End Sub

如何根据单元格的值更改单元格的背景颜色?

【问题讨论】:

    标签: asp.net vb.net gridview


    【解决方案1】:

    试试这个:

    Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView2.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
                If e.Row.Cells(4).Text = "Formation" Then
                    e.Row.Cells(4).BackColor = Color.Red
                End If
        End If
    End Sub
    

    还要在

    上放一个断点
    If e.Row.Cells(4).Text = "Formation" Then
    

    并检查e.Row.Cells(4).Text 的值并确保它真的是="Formation",也许您需要获取Cells(4) 中标签的值。

    【讨论】:

    • 请记住 OnRowDataBound 事件会为您的 gridview 中的每一行触发,因此无需将其放入 foreach 循环中。
    【解决方案2】:

    尝试CellFormatting 事件并删除其中的 for each。该事件针对每个单元格运行。

    Private Sub grd_CellFormatting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles GridView2.CellFormatting
        If GridView2.Item(4,e.RowIndex).Value = "Formation" Then
            e.CellStyle.BackColor = Color.Red
        End If
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-23
      • 2013-06-28
      • 1970-01-01
      • 1970-01-01
      • 2014-09-30
      • 2011-04-03
      相关资源
      最近更新 更多