Full Version: Multi Select List Boxes - Populating A Second List Box From Selection In First List Box
UtterAccess Discussion Forums > Microsoft® Access > Access Forms
jodidew
I have 2 unbound list boxes on my form.

The first list box is based off a query and lists the States.

I would like the second list box to be populated with cities based off of what states the user selects.

I can not get my code to work. Can anyone help?

Private Sub lstStates_AfterUpdate()

Dim varItem As Variant
Dim strCriteria As String
Dim strSQL As String

For Each varItem In Me!lstStates.ItemsSelected
strCriteria = strCriteria & ",'" & Me!lstStates.ItemData(varItem) & "'"
Next varItem

strCriteria = Right(strCriteria, Len(strCriteria) - 1)

strSQL = "SELECT * FROM tblStatesCites " & _
"WHERE tblStatesCites.States IN(" & strCriteria & ");"

lstCities.ListSource = Array(strSQL)

End Sub
Alan_G
Hi

try changing this line

lstCities.ListSource = Array(strSQL)

to

CODE
Me.lstCities.RowSource = strSQL
Doug Steele
List boxes don't have a ListSource property: they have a RowSource property. As well, your Array statement is incorrect: you'd need to have the recordset returned by the SQL string in order for it to be doing anything.

Try:

CODE
Private Sub lstStates_AfterUpdate()
  
Dim varItem As Variant
Dim strCriteria As String
Dim strSQL As String
  
  If Me!lstStates.ItemsSelected.Count > 0 Then
    For Each varItem In Me!lstStates.ItemsSelected
      strCriteria = strCriteria & ",'" & Me!lstStates.ItemData(varItem) & "'"
    Next varItem
  
    strCriteria = Mid(strCriteria, 2)
    strSQL = "SELECT * FROM tblStatesCites " & _
      "WHERE tblStatesCites.States IN(" & strCriteria & ");"
  Else
    strSQL = "SELECT * FROM tblStatesCites "
  End If  
  
  lstCities.RowSource = strSQL
  lstCities.RowSourceType = "Table/Query"
  
End Sub


You might consider putting an ORDER BY clause in your SQL statement to be more user-friendly. As well, it's generally considered a bad idea to use SELECT *, especially for the RowSource of a list box or combo box. Consider explicitly listing the fields of interest.
jodidew
Thank you so much! And good idea about the ORDER. I will do that too.

Jodi
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.