检测网格视图中的重复行

时间:2013-12-26 00:54:01

标签: asp.net vb.net gridview

在我的gridview中,我有一些重复的行,我想用红色显示这些行,如果这些行的前4列类似,那么这些行是重复的。 例如,在这张图片中,第二行和第三行应该变成红色:

enter image description here

这是我的代码:

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    For i = 0 To GridView2.Rows.Count - 1
        If (GridView2.Rows(i).Cells(0).Text = GridView2.Rows(i + 1).Cells(0).Text And GridView2.Rows(i).Cells(1).Text = GridView2.Rows(i + 1).Cells(1).Text And GridView2.Rows(i).Cells(3).Text = GridView2.Rows(i + 1).Cells(3).Text And GridView2.Rows(i).Cells(4).Text = GridView2.Rows(i + 1).Cells(4).Text) Then
            GridView2.Rows(i).ForeColor = System.Drawing.Color.Red
        End If
    Next
End Sub

但是这段代码对我不起作用,其他任何建议都要实现这一点!

谢谢你的时间!

2 个答案:

答案 0 :(得分:1)

如果您使用数据表来填充datagridview,则可以使用defaultview 或者你可以循环遍历所有datagridview项目

For i = 0 To GridView2.Rows.Count - 1
    For j As integer = 0 To GridView2.Rows.Count - 1
        If Not i = j Then
            If (GridView2.Rows(i).Cells(0).Text = GridView2.Rows(j).Cells(0).Text And GridView2.Rows(i).Cells(1).Text = GridView2.Rows(j).Cells(1).Text And GridView2.Rows(i).Cells(3).Text = GridView2.Rows(j).Cells(3).Text And GridView2.Rows(i).Cells(4).Text = GridView2.Rows(j).Cells(4).Text) Then
            GridView2.Rows(i).ForeColor = System.Drawing.Color.Red
            End If
        End If
    Next
Next

答案 1 :(得分:0)

您应该在RowDataBound事件中编写数据格式代码,如下所示。

Protected Sub GridView2_RowDataBound(ByVal sender As GridView, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView2.RowDataBound

    If e.Row.RowType = DataControlRowType.DataRow Then

        Dim idxPrev As Integer = e.Row.RowIndex - 1
        If 1 <= e.Row.RowIndex Then
            If e.Row.Cells(0).Text = sender.Rows(idxPrev).Cells(0).Text AndAlso
                e.Row.Cells(1).Text = sender.Rows(idxPrev).Cells(1).Text AndAlso
                e.Row.Cells(3).Text = sender.Rows(idxPrev).Cells(3).Text AndAlso
                e.Row.Cells(4).Text = sender.Rows(idxPrev).Cells(4).Text Then
                e.Row.ForeColor = Drawing.Color.Red
                sender.Rows(idxPrev).ForeColor = Drawing.Color.Red
            End If
        End If

    End If

End Sub