There are several issues:
1. The SubItem index for itemI was not incremented. See below
If itemI.SubItems(0).Text = itemJ.SubItems(0).Text AndAlso _
itemI.SubItems(1).Text = itemJ.SubItems(1).Text AndAlso _
itemI.SubItems(2).Text = itemJ.SubItems(2).Text AndAlso _
itemI.SubItems(3).Text = itemJ.SubItems(3).Text AndAlso _
itemI.SubItems(4).Text = itemJ.SubItems(4).Text AndAlso _
itemI.SubItems(5).Text = itemJ.SubItems(5).Text AndAlso _
itemI.SubItems(6).Text = itemJ.SubItems(6).Text AndAlso _
itemI.SubItems(7).Text = itemJ.SubItems(7).Text AndAlso _
itemI.SubItems(8).Text = itemJ.SubItems(8).Text Then
2. When you
Remove
an item, the index number of all of the items with higher index numbers is decremented by one.
3. I am not sure about the second
For
statement. I would use this:
For j As Integer = ListView1.Items.Count - 1 to 0 Step -1
4. Need to add a check to ensure you are not comparing the same entry to itself.
If i<>j then
If itemI.SubItems(0).Text = itemJ.SubItems(0).Text AndAlso _
itemI.SubItems(1).Text = itemJ.SubItems(1).Text AndAlso _
itemI.SubItems(2).Text = itemJ.SubItems(2).Text AndAlso _
itemI.SubItems(3).Text = itemJ.SubItems(3).Text AndAlso _
itemI.SubItems(4).Text = itemJ.SubItems(4).Text AndAlso _
itemI.SubItems(5).Text = itemJ.SubItems(5).Text AndAlso _
itemI.SubItems(6).Text = itemJ.SubItems(6).Text AndAlso _
itemI.SubItems(7).Text = itemJ.SubItems(7).Text AndAlso _
itemI.SubItems(8).Text = itemJ.SubItems(8).Text Then
ok = MsgBox("A duplicate item is added,please remove the new item", vbCritical + vbOKCancel, _
"Bridge Construction Cost Estimate")
If ok = vbOK Then
ListView1.Items.Remove(itemJ)
End If
End If
Check for duplicate before adding an item to the ListView control.
Dim itemJ As ListViewItem
Dim bFound As Boolean = False
For j As Integer = 0 To ListView1.Items.Count - 1
itemJ = ListView1.Items(j)
If payItem.ToString() = itemJ.SubItems(0).Text AndAlso _
subpayItem.ToString() = itemJ.SubItems(1).Text AndAlso _
subItem = itemJ.SubItems(2).Text AndAlso _
unit = itemJ.SubItems(3).Text AndAlso _
bridgeType = itemJ.SubItems(4).Text AndAlso _
span = itemJ.SubItems(5).Text AndAlso _
quantity.ToString() = itemJ.SubItems(6).Text AndAlso _
Rate.ToString() = itemJ.SubItems(7).Text AndAlso _
amount.ToString = itemJ.SubItems(8).Text Then
bFound = True
Exit For
End If
Next
If bFound Then
Msgbox("Cannot add a duplicate item")
Else
ListView1.Items.Add(payItem.ToString()).SubItems.AddRange({subpayItem.ToString(), subItem, unit, _
bridgeType, span, quantity.ToString(), Rate.ToString(), amount.ToString()})
End If