2017-04-17 57 views
0

我遇到問題,防止將重複項添加到列表框。當列表框包含從保存文件加載的項目時,防止重複項添加到列表框問題

  • 我的Windows窗體有2個列表框
  • 的形式被設計成當用戶點擊一個按鈕,他們在第一箱已檢查的項目將被添加到第二個框
  • 下面的代碼,我已添加到「添加」按鈕的目的是爲了防止方框1中的選中項目被添加到方框2如果方框2中存在相同的項目。
  • 我的代碼的問題是它不會停止重複如果方框2包含從保存文件加載的項目,則從添加到方框2。

有關如何解決此問題的任何想法?

Public Sub additems_Click(sender As Object, e As EventArgs) Handles additems.Click 

    Dim itemChecked As Object 
    Dim alreadyonkey As Boolean 
    Dim duplicates As Integer = 0  

    If box1.CheckedItems.Count > 0 Then 
     For Each itemChecked In box1.CheckedItems 
      alreadyadded = False 
      'Check if item selected has already been added to box2 
      If box2.Items.Contains(itemChecked) = True Then 
       alreadyadded = True 
       duplicates = duplicates + 1 
      Else 
       alreadyadded = False 
      End If 

      'Add item if all criteria met 
      If box2.Items IsNot "" And alreadyadded = False Then 
       box2.Items.Add(itemChecked) 
      End If 
     Next 

     If duplicates > 0 Then 
      MsgBox("One or more of the items you are trying to add have already been added.", MsgBoxStyle.Critical, "Item has already been added") 
      alreadyadded = False 
     End If 
    End If 

末次

+0

是列表框還是checkedlistbox?您可以使用包含「Selected」或類似屬性的類以及它們的集合作爲數據源。第一個會篩選那些未被選中的列表,另一個則是相反的。 – Plutonix

+0

Box1是一個checkedlistbox。 Box2只是一個普通的列表框。使用該方法的問題是Box1中可供選擇的項目是基於在單獨的組合框中選擇哪個索引而生成的。 –

回答

0

我想通了,這個問題我的代碼......這個問題主要是由於一個嵌套的每個所需要的循環將用於每個項目BOX1比較每個事實box2中的項目一次一個,並且需要將項目發送到字符串變量,並使用「String.Equals」進行比較。

Public Sub additems_Click(sender As Object, e As EventArgs) Handles additems.Click 

    Dim itemChecked As Object 
    Dim alreadyadded As Boolean 
    Dim duplicates As Integer = 0 


    If box1.CheckedItems.Count > 0 
     For Each itemChecked In box1.CheckedItems 
      Dim itemtoadd As String = itemChecked.ToString 

      'Check if item selected has already been added to box2 
      For Each item In box2.Items 
       Dim box2item As String = item.ToString 

       If String.Equals(Trim(itemtoadd), Trim(box2item)) = True Then 
        alreadyadded = True 
        duplicates = duplicates + 1 
       Else 

       End If 
      Next 

      'Add item if all criteria met 
      If itemChecked IsNot "" And alreadyadded = False Then 
       box2.Items.Add(itemChecked) 
      End If 
     Next 


     If duplicates > 0 Then 
      MsgBox("One or more of the items you are trying to add have already been added.", MsgBoxStyle.Critical, "Item hase already been added") 
      alreadyadded = False 
      duplicates = 0 
     End If 
    End If