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

3
我需要更改我的网格视图单元格的背景颜色,但是它没有起作用。
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个回答

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
请记住,OnRowDataBound事件会为您的GridView中的每一行触发一次,因此无需将其放入foreach循环中。 - coster128

1
尝试使用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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接