Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

list box multi select?

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hello
i want to use a list box control with the multiselect property set to 1 (simple), what i thought would work to know the selected items from the list is

dim i as integer, a() as integer
for i=1 to list.listcount
if list.item(i).selected=True then a(i)=i
else a(i)=0
end if
next i
this didin't work and don't know why. i know this might seem too silly, but does any one know how can i do it?
many thanks
Amal
 
Hi amalandamal,

Try This:-

Dim i As Integer
Dim a() As Integer 'Must ReDimension Array

'Listbox Listcount starts from Zero
For i = 0 To List1.ListCount - 1
ReDim Preserve a(i) 'ReDimension Array

If List1.Selected(i) = True Then
a(i) = i
Else
a(i) = 0
End If
Next


Regards,

Codefish
 
Rather than ReDim inside the loop,
why not ReDim once, before the loop
ReDim a(list1.listcount)

It's trivial for a small listbox, but you're rewriting
the entire array unnecessarily for each item in the list.

scarfhead
 
Either way is either unnecessarily declaring an array or creating an array too large.

Try this:

Code:
Dim i As Integer, a() As Integer
ReDim a(List1.SelCount)

For i = 0 To List1.ListCount - 1
   If List1.Selected(i) = True Then a(i) = i
Next i
 
It seems you should set a(i) = true or 1 not a(i) = i, was that a typo???

Here is some code I use to do something similar that works...

Dim i As Integer, x As Integer, cnt As Integer
cnt = 0
For i = 0 To ListFRID.ListCount - 1
If ListFRID.Selected(i) Then
cnt = cnt + 1
End If
Next
If cnt > 0 Then
ReDim sFRIDS(cnt - 1)
x = 0
For i = 0 To ListFRID.ListCount - 1
If ListFRID.Selected(i) Then
sFRIDS(x) = ListFRID.List(i)
x = x + 1
End If
Next
 
There's no need to create a loop to find out how many of the items are selected.

The listbox has a .SelCount which is the count of the selected items.. It's an unnecessary Step.

--NipsMG
 
NipsMG,

You can't use ReDim a(List1.SelCount) because you will get a subscript out of range error in some cases.

i.e. when the selected List Item index value is > number of selected items in the listbox.

Codefish
 
you are absolutely correct about that one.. now that I think about it.

However, all you need to do is create another increment variable

dim iArray as integer
redim a(list.SelCount)
iArray = 0
for i = 0 to list.listcount - 1
if list.selected(i) then
a(iArray) = list.list(i)
iArray = iArray + 1
end if
next i
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top