如何根据其值更改gridview单元格背景颜色

时间:2015-06-07 19:11:38

标签: asp.net vb.net gridview

我需要更改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

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

2 个答案:

答案 0 :(得分: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)中标签的值。

答案 1 :(得分:1)

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

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