|
-
Jun 3rd, 2000, 11:08 PM
#1
Thread Starter
PowerPoster
The issue is this: When you have a listbox that has its multi-select property set to something other than "None" (i.e., "Simple" or "Extended"), and you allow the user to remove items from the listbox, what is the best way to code the "remove" logic?
I have been using my own solution to this issue for quite some time, but I would like some feedback from other programmers. Please tell me either:
(1) Yes, Bruce, this is a fine way of doing this!
-or-
(2) What are you, crazy? There's a much better way to do this! (And of course tell me what it is.)
The code samples below refer to what would be behind the "Remove" command button that the user would click after making their selections from the list.
First of all, we can all appreciate that the following is the WRONG way to remove multiple items from a list box:
Code:
'Wrong logic
Dim X As Integer
For X = 0 To List1.ListCount - 1
If List1.Selected(intListX) Then
List1.RemoveItem X
End If
Next
The reason that the above code is wrong is that as you remove items from the list, VB automatically adjusts the ListCount property. So as you go through the above loop and remove items, the loop control variable (X in this case) becomes out of sync with the ListCount property, and you typically wind up with a value in the loop control variable that is not a valid array element for the list box, resulting in an "Invalid property value" run-time error.
The way I've been solving this problem is to change the For loop to use a Boolean variable that I set when I remove a selected item from the list, and then exit the For loop at that time. The For loop is nested within a Do loop that checks the Boolean variable to see whether or not an item was removed on that pass. As long as an item was removed, the Do loop continues. If no item was removed on a given pass, we know that there are no more selected items in the list to remove, so the Do loop can terminate.
This works, and seems reasonably fast. But is it unecessarily complicated? Is there a simpler way to do this that I have overlooked? This has just been a nagging question for me for a while.
Here's my code:
Code:
Dim X As Integer
Dim intStart As Integer
Dim intNewStart As Integer
Dim blnItemWasSelected As Boolean
intStart = 0
intNewStart = 0
Do
blnItemWasSelected = False
intStart = intNewStart
For X = intStart To List1.ListCount - 1
If List1.Selected(X) Then
intNewStart = X
List1.RemoveItem X
blnItemWasSelected = True
Exit For
End If
Next
Loop While blnItemWasSelected
Thanks in advance for your input.
[Edited by BruceG on 06-04-2000 at 04:37 PM]
"It's cold gin time again ..."
Check out my website here.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|