2

我需要遍历gridview中的特定列。例如,我需要循环每个“%”列,然后根据它们的值分配颜色,有没有简单的方法来实现呢?谢谢。

网格视图表 在此处输入图像描述

行数据绑定事件

    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
4

1 回答 1

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

我假设,无论出于何种原因,您只想突出显示 10 月至 12 月的数字。如果您想改变,或者想为其他季度使用不同的颜色,请说出来。

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
于 2012-09-26T00:01:24.300 回答