VISUAL BASIC PROBLEM

Problem Code VBPBLST001

Description

How To remove multiple item from THE LISTBOX.

VB Version Compatibility

This solution is tested in VB6 and expected to work in VB5 and VB4.

Theory

LISTBOX Custom Control provides REMOVEITEM method to delete item from it. It takes position of item as an argument and remove it from the LISTBOX.

Since this method remove one item at a time therefor in order to remove more that one item we need to use REMOVEITEM method inside the loop.

Solution

  1. Open a new VB project
  2. Add a FORM , if not added automatically
  3. Put a LISTBOX and command button control on form.
  4. Change the multiselect property of LISTBOX to 2.
  5. Do not change name of any Controls or the FORM.
  6. On Load() event of FORM add following lines.

Private sub Form_Load()

   List1.AddItem "ITEM 0"  
   List1.AddItem "ITEM 1"
   List1.AddItem "ITEM 2"
   List1.AddItem "ITEM 3"
   List1.AddItem "ITEM 4"
End Sub
  1. Now add the following lines of code in the click() event of Command button.

Private sub Command1_Click()

Dim I As Integer
    For I = List1.ListCount - 1 To 0 Step –1 ' NOTE
       If List1.Selected(I) Then
          List1.RemoveItem I
       End If
    Next
End Sub
  1. Run the project and select some items from the LISTBOX and press COMMAND BUTTON. you will see that selected items is removed from the LISTBOX.

Note  Key to this problem is using Loop in descending order. because if you use Loop from 0 to list1.listcount - 1, it would generate runtime error because after deleting every item from the LISTBOX all items are re-numbered. 

e.g, if you want to remove 3rd and 4th item from LISTBOX and if you put loop from 0 to list1.listcount -1 then after removing 3rd item from the LISTBOX 4th item become 3rd item and when Loop reaches to the 4th item it would not found the 4th item and generate error.

--------------------X-X-X-X-X-X-X-X--------------------

SPECIAL NOTE :- ALTHOUGH this is tip is tested thoroughly. Using this tip is at user own risk. Visual Code is not responsible for any damage caused directly or indirectly.

BACK

  1