user4274765
user4274765

Reputation:

Listbox items delete

How can I delete my listbox item text after Contains "?" ?

Example listbox item text:

I want it ? please, remove it.

My code:

        For i = 0 To ListBox1.Items.Count - 1

        If ListBox1.Items(i).ToString.StartsWith("?") Then
        'something useful for me.
        End If
        Next

If I want to delete specific text then I use it.

For i = 0 To CheckedListBox1.Items.Count - 1
            If CheckedListBox1.Items(i).ToString.Contains("something") Then
                CheckedListBox1.Items(i) = CheckedListBox1.Items(i).ToString.Replace("something", "")
            End If

But it's dynamically generated listbox items. Example:

I want it ? please, remove it.1234
I want it ? please, remove it.2345
I want it ? please, remove it.64653
I want it ? remove461
etc...

Upvotes: 0

Views: 399

Answers (1)

Steve
Steve

Reputation: 216293

Start looping backwards and then use RemoveAt

For i = ListBox1.Items.Count - 1 To 0 Step -1
    If ListBox1.Items(i).ToString.StartsWith("?") Then
       ListBox1.Items.RemoveAt(i)
    End If
Next

When you want to remove one or more items from a collection is important to loop from the end of the collection towards its first element. If you loop in the normal forward mode you could have problems when you remove an item. For example, if you remove an item at position 5, the item at position 6 shifts in position 5 but then you increment the loop indexer to 6 effectively jumping your logic for the item that was previously at position 6

UPDATE: If you want to remove an item that contains the question mark then use a different method to check for the question mark existance in the examined item

For i = ListBox1.Items.Count - 1 To 0 Step -1
    If ListBox1.Items(i).ToString.Contains("?") Then
       ListBox1.Items.RemoveAt(i)
    End If
Next

Or, if you want to replace the current item that contains a question mark clipping away the text after the question mark write something like this

For i = ListBox1.Items.Count - 1 To 0 Step -1
    If ListBox1.Items(i).ToString.Contains("?") Then
       Dim item = ListBox1.Items(i).ToString()
       Dim pos = item.IndexOf("?"c)
       item = item.Substring(0, pos)
       ListBox1.Items(i) = item
    End If
Next

Eventually, if the question mark is surrounded by spaces you could add a TrimEnd

 item = item.Substring(0, pos).TrimEnd()

Upvotes: 1

Related Questions