比较ListViewItems与SelectedItems

时间:2019-03-08 17:20:56

标签: vb.net winforms listview

我遇到以下问题:

我有一个ListView,例如5个项目:

AAAA (selected)
BBBB 
CCCC (selected)
AAAA (selected)
AAAA

然后我将检查是否选择了所有相同的项目(例如,在此处还选择了CCCC等其他项目),否则我将收到带有错误消息的Msgbox。

在此示例中,由于缺少一个AAAA项目,因此应该得到错误消息。

这是我尝试过的方法,但是在这种情况下,如果您选择其他项目,则只能使用一个,例如AAAA正在运行。 (AAAA和BBBB无法正常工作)

ContainerBox是ListView

Dim SelectedContainer As Integer = ContainerBox.SelectedItems.Count - 1
Dim ContainerXY As String
Dim ContainerXYAnzahl As Integer
Dim ContainerXYAnzahlAusge As Integer

For i As Integer = 0 To SelectedContainer
    ContainerXY = ""
    ContainerXYAnzahl = 0
    ContainerXYAnzahlAusge = 0
    ContainerXY = ContainerBox.SelectedItems(i).ToString.Substring    (ContainerBox.SelectedItems(i).ToString.IndexOf(":") + 1)
    For ii As Integer = 0 To ContainerBox.Items.Count - 1
        If ContainerXY = ContainerBox.Items(ii).ToString.Substring (ContainerBox.Items(ii).ToString.IndexOf(":") + 1) Then
           ContainerXYAnzahl += 1
        End If
    Next
    For ii = 0 To SelectedContainer
        If ContainerXY = ContainerBox.SelectedItems(i).ToString.Substring(ContainerBox.SelectedItems(i).ToString.IndexOf(":") + 1) Then
        ContainerXYAnzahlAusge += 1
        End If
    Next
    If ContainerXYAnzahlAusge <> ContainerXYAnzahl Then
        PresentPopup("Bitte wählen Sie alle Positionen" & Environment.NewLine & "des Container", AlertType._Error)
        Exit Sub
    End If
Next

这是ListView的样子:

ListView

1 个答案:

答案 0 :(得分:0)

尝试一下

Private Sub ListView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListView1.SelectedIndexChanged
    Dim selectedList = ListView1.SelectedItems.OfType(Of ListViewItem)
    Dim desiredList = ListView1.Items.OfType(Of ListViewItem).Where(Function(i) selectedList.Select(Function(j) j.Text).Contains(i.Text))
    Dim missingItems = desiredList.Except(selectedList)
    Dim selectionsCorrect = Not missingItems.Any()
    Me.Text = $"Correct: {selectionsCorrect}; Missing items: ({String.Join(", ", missingItems.Select(Function(i) i.Text))})"
End Sub