neverlucky
neverlucky

Reputation: 35

ListView delete line with matching field

i have a listview like the following:

Name  | Gender | Age
---------------------
Name1 |   XX   | 23
Name2 |   XY   | 21
Name3 |   XY   | 25
Name4 |   XX   | 30

When the listview gets filled, it creates entries of a combobox like this:

If Not ComboBox4.Items.Contains(gender) Then
    ComboBox4.Items.Add(gender)
End If

So I end up with a combobox with 2 entries (XX, XY). Now i want to delete all lines matching to the gender selected in the combobox. The seleted entry then gets removed from the combobox.
Example: I select gender 'XX' to be removed, then the program removes the whole line with 'name1, XX , age 23' and 'name4, XX, 30' from the listview.

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    for i = 1 to viewlist.items.count
        'Need help here to select the right column/viewlist-field
    next
    ComboBox4.Items.Remove(ComboBox4.Text)
End Sub

Thanks in advance

Upvotes: 0

Views: 96

Answers (1)

Visual Vincent
Visual Vincent

Reputation: 18310

First of all, your loop should start at viewlist.Items.Count - 1 and end at 0. This is because the right side of To is only evaluated prior to the first iteration. Due to this the loop will go to whatever viewlist.Items.Count - 1 was before the loop was run, instead of what it actually is after removing items (hence why you got the ArgumentOutOfRangeException from my previous code).

By starting from the end and going towards 0 i will always represent a valid index as long as you remove at most one item per iteration. This can be illustrated by the following:

First iteration    Second iteration    Third iteration    (and so on)
    Item 0             Item 0              Item 0
    Item 1             Item 1          (i) Item 1
    Item 2         (i) Item 2              [Removed]
(i) Item 3             [Removed]           [Removed]

Now, to get a sub-column of an item you can use the ListViewItem.SubItems property. Your Gender column is currently at index 1 - the first sub-item (index 0) is apparently the owner of all sub-items, that is, the original ListViewItem.

For i = viewlist.Items.Count - 1 To 0 Step -1
    Dim CurrentSubItems As ListViewItem.ListViewSubItemCollection = viewlist.Items(i).SubItems
    If CurrentSubItems.Count >= 2 AndAlso CurrentSubItems(1).Text = ComboBox4.Text Then
        viewlist.Items.RemoveAt(i)
    End If
Next
ComboBox4.Items.Remove(ComboBox4.Text)

If you want to use case-insensitive string comparison you can change the If-statement in the loop to:

If CurrentSubItems.Count >= 2 AndAlso String.Equals(CurrentSubItems(1).Text, ComboBox4.Text, StringComparison.OrdinalIgnoreCase) Then

Upvotes: 1

Related Questions