XTab's Blog

Ged Mead's Blog at vbCity

vbCity Blogs moved to:
http://cs.vbcity.com/blogs
  Home :: Syndication  :: Login

OctNovember 2009Dec
SMTWTFS
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

Archives

Topics

Ramblings

VB.NET

  This is something that seems to come up fairly often in the Forums. Someone wants to test for a particular value in a ListBox and if the list does (or doesn't) contain the value then that item is to be deleted.

  One common way of doing this would be to use the Contains function to test if the target character or substring exists in the ListBox.

   This isn't a particular difficult task, but the thing that usually catches most beginners out here is that you have to traverse the ListBox items in reverse order. Well, you do if you actually end up deleting any items, anyway. The reason being that if you start from the top and work down, then as soon as you delete an item the ListBox's indices get out of sync and an ArgumentOutOfRange Exception will be thrown and you will get a message along the lines of the one shown below:

   In a recent post, a slight variation on this theme was that the check was to be made in one ListBox and if the required search string wasn't found in that first ListBox then not only was the item in the first ListBox to be deleted but also the corresponding item number in a second ListBox was also to be deleted.

  Again this is straightforward and the following code will do the job :

Code Copy
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        For i As Integer = ListBox1.Items.Count - 1 To 0 Step -1
            If Not ListBox1.Items(i).Contains(TextBox1.Text) Then
                ListBox1.Items.RemoveAt(i)
                ListBox2.Items.RemoveAt(i)
            End If
        Next
    End Sub

  As I say, it's not rocket science, but that traversing upwards trick is something worth knowing for these kind of situations.

posted on Tuesday, February 19, 2008 5:26 PM