开发者

ListView delete item by name using VB.net

开发者 https://www.devze.com 2023-02-17 18:44 出处:网络
I was just wondering if it was possible to delete an item from a listview just knowing its text name (as in listbox.text) without the need开发者_如何学Go to know the index or have it selected/highligh

I was just wondering if it was possible to delete an item from a listview just knowing its text name (as in listbox.text) without the need开发者_如何学Go to know the index or have it selected/highlighted?

 Dim lvi As ListViewItem
 Dim lvi2 As ListViewItem

    For Each lvi In lstMaster.Items
        For Each lvi2 In lstNew.Items
            If lvi.Text = lvi2.text Then
                'Remove the item using its TEXT..
                'Eample:
                'lstMaster        | lstNew
                '--------------------------------------
                'Bob              | Jenny
                'Jason            |
                'Jenny            |
                'Zac              |
                '--------------------------------------
                'The program should delete "Jenny" from the lstMaster....
            End If
        Next
    Next

Thanks!

David


I dont see why you couldn't use the text property. Is there any reason why you cant do this though:

If lvi.Text = lvi2.Text Then
    lstMaster.Items.Remove(lvi)
End If


This code should work for you:

Dim lvw As New ListView()

lvw.Items.AddRange({New ListViewItem("Item 1"),
                    New ListViewItem("Item 2"),
                    New ListViewItem("Item 3")})

lvw.Items.Remove((From i In lvw.Items.OfType(Of ListViewItem)() 
                  Where i.Text = "Item 1").First)

It uses LINQ to find the item with the text "Item 1" and then it removes it from the ListView's ListViewItemCollection (the Items property).

The minor caveat here is that there must be an Item with the text "Item 1" otherwise the First() extension method will fail. If you are unsure, you can use FirstOrDefault() or pre-check the LINQ statement contains a value before proceeding with the item removal.

Edit

This is the updated code to match your updated requirement:

For Each lvi in lstNew.Items
    Dim masterItem = From i in lstMaster.Items.OfType(Of ListViewItem)()
                     Where i.Text = lvi.Text
    
    If masterItem.Any Then
        lstMaster.Items.Remove(masterItem.First)
    End If
Next


You can just copy the list from which you want to delete items, like this:

For Each lvi In lstMaster.Items.ToList
    For Each lvi2 In lstNew.Items
        If lvi.Text = lvi2.text Then
            lstMaster.Items.Remove(lvi)
        End If
    Next
Next

That way you don't have the problem of deleting items from the list you're currently enumerating.

0

精彩评论

暂无评论...
验证码 换一张
取 消