如何根据网格视图的值改变网格的背景颜色

时间:2021-06-25 19:40:38

I need to change the background color of the cells of my gridview, but it doesn't work.

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

How do I change the background color of a cell based on its value?

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

2 个解决方案

#1


1  

Try this:

试试这个:

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

Also put a break point on

还要设置一个断点

If e.Row.Cells(4).Text = "Formation" Then

and check the value of e.Row.Cells(4).Text and make sure it is really = "Formation", maybe you need to get the value of the label that is in Cells(4).

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

#2


1  

try the CellFormatting event and remove the for each in it. The event runs for every cell.

尝试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

#1


1  

Try this:

试试这个:

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

Also put a break point on

还要设置一个断点

If e.Row.Cells(4).Text = "Formation" Then

and check the value of e.Row.Cells(4).Text and make sure it is really = "Formation", maybe you need to get the value of the label that is in Cells(4).

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

#2


1  

try the CellFormatting event and remove the for each in it. The event runs for every cell.

尝试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