我需要在gridview中循环遍历特定列。例如,我需要循环每个“%”列,然后根据它们的值分配颜色,是否有一种简单的方法来实现它?感谢。
Gridview表
RowDataBound事件
Protected Sub gv_ssi_rzli_data_1_RowDataBound(sender As Object, e As EventArgs) Handles gv_ssi_rzli_data_1.RowDataBound
Dim gv As GridView = gv_ssi_rzli_data_1
For i As Integer = 0 To gv.Rows.Count - 1
If gv.Rows(i).Cells(0).Text = "Oct" Or
gv.Rows(i).Cells(0).Text = "Nov" Or
gv.Rows(i).Cells(0).Text = "Dec" Then
If gv.Rows(i).Cells(2).Text >= Session("rzli_avg_blue_1") Then
gv.Rows(i).Cells(2).BackColor = System.Drawing.Color.LightBlue
ElseIf gv.Rows(i).Cells(2).Text >= Session("rzli_avg_green_1") And gv.Rows(i).Cells(2).Text < Session("rzli_avg_blue_1") Then
gv.Rows(i).Cells(2).BackColor = System.Drawing.Color.LightGreen
ElseIf gv.Rows(i).Cells(2).Text >= Session("rzli_avg_yellow_1") And gv.Rows(i).Cells(2).Text < Session("rzli_avg_green_1") Then
gv.Rows(i).Cells(2).BackColor = System.Drawing.Color.LightYellow
ElseIf gv.Rows(i).Cells(2).Text <= Session("rzli_avg_red_1") Then
gv.Rows(i).Cells(2).BackColor = System.Drawing.Color.LightPink
End If
End If
Next
End Sub
答案 0 :(得分:0)
有很多方法可以做到这一点。
首先,我应该指出,每次绑定行时,您似乎都在阅读整个网格,这似乎是不必要的。
除此之外,也许最简单的方法是将与您的值范围进行比较的代码抽象为自己的方法,并将参数作为要测试和修改的单元格。由于我假设您使用列索引2知道哪些列是百分比列,因此您只需使用相关单元调用新方法,如下所示:
For i As Integer = 0 To gv.Rows.Count - 1
Dim row = gv.Rows(i)
Dim rowHeaderCell = row.Cells(0)
if rowHeadercell.Text = "Oct" Or
rowHeaderCell.Text = "Nov" or
rowHeaderCell.Text = "Dec" Then
SetCellBackGround(row.Cells(2))
SetCellBackground(row.Cells(4))
' etc.
End If
Next
我认为,无论出于何种原因,您只想强调Oct-Dec数字。如果您想要改变,或者想要为其他季度使用不同的颜色,请说明。
SetCellBackground看起来像这样(从内存中输入):
Sub SetCellBackground(TableCell cell)
If cell.Text >= Session("rzli_avg_blue_1") Then
cell.BackColor = System.Drawing.Color.LightBlue
ElseIf cell.Text >= Session("rzli_avg_green_1") And cell.Text < Session("rzli_avg_blue_1") Then
cell.BackColor = System.Drawing.Color.LightGreen
ElseIf cell.Text >= Session("rzli_avg_yellow_1") And cell < Session("rzli_avg_green_1") Then
cell = System.Drawing.Color.LightYellow
ElseIf cell <= Session("rzli_avg_red_1") Then
cell.BackColor = System.Drawing.Color.LightPink
End If
End Sub