[asp.net]Gridview 比较当前行的上一行

发布时间: 2016/8/20 3:59:25
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我想格式化 gridview 基于当前的行值 (列 2) 与以前的行值进行比较。 所以如果他们相同的背景色将相同,说绿色。 如果他们是不一样的背景色会变成红色。 例如︰

Gridview values
Car 1 (bg color green)
Car 1 (bg color green)
Car 2 (bg color red)
Car 3 (bg color green)
Car 3 (bg color green)
Car 3 (bg color green)

我已经不能够得到这个工作。 这里是我赶上了的代码。

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowCreated

    If e.Row.RowType = DataControlRowType.DataRow Then

        If Not e.Row.DataItem Is Nothing Then

            'switch for first row 
            If e.Row.RowIndex = 1 Then
                Dim Gprev As GridViewRow = GridView1.Rows(e.Row.RowIndex - 1)
                If Gprev.Cells(1).Text = e.Row.Cells(1).Text Then
                    'e.Row.Cells(1).Text = ""
                    e.Row.BackColor = Drawing.Color.Red
                End If
            End If

            'now continue with the rest of the rows
            If e.Row.RowIndex > 1 Then

                'set reference to the row index and the current value
                Dim intC As Integer = e.Row.RowIndex
                Dim lookfor As String = e.Row.Cells(1).Text

                'now loop back through checking previous entries for matches 
                Do
                    Dim Gprev As GridViewRow = GridView1.Rows(intC - 1)

                    If Gprev.Cells(1).Text = e.Row.Cells(1).Text Then
                        'e.Row.Cells(1).Text = ""
                        e.Row.BackColor = Drawing.Color.Red
                    End If

                    intC = intC - 1
                Loop While intC > 0

            End If

        End If

    End If

End Sub

解决方法 1:

代码在 c# 中但希望易足以转换...

在 RowDataBound...

if (e.RowType != DataControlRowType.DataRow) return;  
if (e.Row.DataItemIndex ==0)  
{  
  e.Row.Cells[1].BackColor = Color.Green;  
  return;  
}  
var thisRow = e.Row;   
var prevRow = GridView.Rows[e.Row.DataItemIndex-1];  
e.Row.Cells[1].BackColor = (thisRow.Cells[1].Text == prevRow.Cells[1].Text) ? Color.Green : Color.Red;  
}

注意也绿色和红色不与对方 (色盲) 对比一般好的选择

官方微信
官方QQ群
31647020