2014-06-05 32 views
0

我正在研究條碼項目。我可以將掃描的條形碼添加到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  

,但它似乎不工作...它不會改變任何東西......重複仍顯示。

我甚至發現這一點,可以改變重複的顏色爲紅色,並改變了一點,因爲它只需將檢測到以前的索引,但仍然只有相同....

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  |   

或突出顯示重複的文字。

我不知道我的代碼出了什麼問題。

由於在進步....我真的很感激的,但..

+0

您是否使用斷點來檢查代碼停止在哪一行?它是否通過這行'如果e.Row.Cells(3).Text = sender.Rows(idxPrev).Cells(3).Text'?如果是的話,值是否正常? –

+0

代碼不會爲gridview上的每個值循環...它只檢查當前索引中的前一個索引。該行工作,但循環不工作。 –

+0

您不需要在GridView1_RowDataBound事件中使用循環,因爲RowDataBound本身就像一個循環遍歷GridView行,所以只需檢查值並在重複時刪除或突出顯示它。 –

回答

0

算法:刪除重複數據

步驟1:存儲第一行的,第一個單元內容

第2步:從第二行開始遍歷整個網格直到結束 並檢查名稱列的值是否相同。 如果相同,則用空字符串 替換該值,否則繼續使用新值。上述過程將會重演。

//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 
+0

謝謝Pavan。我嘗試了你的建議。但它顯示錯誤「索引超出範圍,必須是非負數,並且小於集合的大小。」 ....在此代碼中:oldvalue = GridView1.Rows(0).Cells(0).Text –

+0

嗯......你有一個數據庫,其中存儲所有的條形碼值?或者你只是想檢查DataGridView中的所有數據? – GoroundoVipa

+0

我有數據庫,然後使用文本框從數據庫中選擇數據,並將其逐個添加到gridview中。數據將被添加到每個輸入中。 –