当列表框包含从保存文件加载的项目时,防止将重复项添加到列表框

时间:2017-04-17 15:03:13

标签: vb.net validation listbox checkedlistbox listboxitems

我遇到了阻止重复项添加到列表框的问题。

  • 我的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

End Sub

1 个答案:

答案 0 :(得分:0)

我想出了我的代码的问题......问题主要是因为需要使用嵌套的For Each循环来将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