Hi BH: Nice to see somebody concerned about "better coding" :-)
A couple of points... first you can avoid constructs like "If AllValues =
True" and simply test the value of the variable. Remember it is a boolean
so it's value is basically the result of the test. So code it as "If
AllValues" and you get the same answer.
Now to the point of better coding. It may be more "efficient" in terms of
time to use the SelectedItems property but that isn't the only measure of
better coding. I'd probably opt for traversing the collection and the
reason is (as you've indicated) you can address them all or the selected
subset. Importantly the same loop could address any other property (not
just selected) so if you had to test for any other condition your code would
be very similar. And similarity is good.
From an efficiency standpoint consider using the For Each syntax in your
second example. So basically your routine will visit every item once, test
it for a condition and do something if that condition is met. That's easy
to understand code, that's hard to break code and so that's "better" code.
Tom
"bh" <No****@ReplyToGroup.comwrote...
If I want to loop through the values in a listbox, and get either all
items in the box, or only selected items, based on a boolean variable
passed into a subroutine, which method would be more efficient?
First Method (test allvalues, first and either loop through all items or
selecteditems, accordingly):
Dim dview As DataRowView
Dim AllValues As Boolean = False
If AllValues = True Then
For Each dview In lstMyListBox.Items
.
.
.
Next
Else
For Each dview In lstMyListBox.SelectedItems (does this
property do a "behind the scenes" if...then, anyway?)
.
.
.
Next
End If
-OR- Second Method (loop through all items, regardless, then check
selected property, if needed):
Dim dview As DataRowView
Dim AllValues As Boolean = False
Dim iIndex As Integer
For iIndex = 0 To lstMyListBox.Items.Count - 1
If AllValues = True OrElse lstMyListBox.GetSelected(iIndex) =
True Then
.
.
.
End If
Next