如何在gridview中查找和删除重复值

时间:2014-06-05 01:46:38

标签: vb.net gridview

我正在从事条形码项目。我可以将扫描的条形码添加到gridview列表中,但是我发现删除扫描的重复条形码有些问题。因此,只要条形码扫描,它就会添加到列表中,即使是列表中已有的条形码也是如此。我希望它突出显示它,以便用户知道哪个条形码是重复的,甚至是删除它。 gridview上的数据来自基于条形码的数据库。

示例表数据:

 Barcode |  Items   |
 001     |  one     |  --> this will be red
 002     |  two     |        
 002     |  two     |  --> this will be red
 001     |  one     | --> this will be red

这是我的代码:

    Protected Sub GridView1_RowDataBound(ByVal sender As GridView, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
  Dim oldvalue, newvalue As String
    oldvalue = String.Empty
    newvalue = String.Empty
    For j As Integer = 0 To j < 2 Step 1
        For i As Integer = 0 To i < GridView1.Rows.Count Step 1
            oldvalue = GridView1.Rows(i).Cells(j).Text
            If oldvalue = newvalue Then
                GridView1.Rows(i).Cells(j).Text = String.Empty
            End If
            newvalue = oldvalue
        Next
    Next

End Sub       

但它似乎不起作用......它没有改变任何东西......副本仍然显示。

我甚至发现这可以将副本的颜色更改为RED,并稍微更改一下,因为它只检测到以前的索引,但仍然是相同的....

Protected Sub GridView1_RowDataBound(ByVal sender As GridView, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
    For Each row As GridViewRow In GridView1.Rows
       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(3).Text = sender.Rows(idxPrev).Cells(3).Text Then
                    e.Row.ForeColor = Drawing.Color.Red
                    sender.Rows(idxPrev).ForeColor = Drawing.Color.Red
                End If
            End If
        End If
    Next

End Sub

此代码只能显示如下内容:

 Barcode |  Items   |
 001     |  one     |  --> this will be red
 001     |  one     |   --> this will be red     
 002     |  two     |  
 001     |  one     | 

预期结果:

 Barcode |  Items   |
 001     |  one     |  
 002     |  two     |        

或突出显示重复的文字。

我不知道我的代码出了什么问题。

谢谢你的进步....我真的很感激,但是......

1 个答案:

答案 0 :(得分:0)

  

算法:删除重复数据

     

步骤1:存储第一行的第一个单元格内容

     

步骤2:从第2行到结束循环整个网格             并检查Name列的值是否相同。       如果相同,则用空字符串替换该值       否则继续使用新值。上述过程将重演。

//Step 1:
Dim oldvalue As String
oldvalue = String.Empty
If GridView1.Rows.Count>0 then
   string oldvalue = GridView1.Rows[0].Cells[0].Text;

   //Step 2:
   For i As Integer = 1 To i < GridView1.Rows.Count Step 1
       If oldvalue = GridView1.Rows[i].Cells[0].Text Then
          GridView1.Rows(i).Cells(0).Text = String.Empty
          GridView1.Rows(i).Cells(1).Text = String.Empty
       Else
          oldvalue=GridView1.Rows[i].Cells[0].Text
       End If
   Next
End If