Access Tree View and List Box Row Source
How to Load a Category Tree and Listbox RowSource Type "Field Value" Property
Overview
In this Access 2000 article, I will show you how to create a category tree and load it into a listbox. I will demonstrate the steps to create a static value list and associate it with a listbox. The algorithm can be easily ported to a treeview control or to HTML for an active server page.
Creating the Category Table
categoryid: autonumber
parentid: number
title: text
Parent ID | Category ID (autonumber) | Title | |
0 | 1 | Hardware | |
0 | 2 | Computers | |
2 | 3 | DeskTop | |
2 | 4 | Server |
Back to Access 2000 How To's Series Home
Add a Listbox
Option Explicit
Option Compare Database
Dim sFieldValues As String
Private Sub Form_Load()
'Heading Column titles
sFieldValues = "Parent Id;Category Id, Title;"
Call LoadCategory(0)
lbxCategory.RowSourceType = "Value List"
lbxCategory.RowSource = sFieldValues
lbxCategory.ColumnCount = 3
lbxCategory.ColumnHeads = True
End Sub
Children are concatenated to the sFieldValues string
Private Sub LoadCategory(sId)
Dim rs As Object
Dim sql
Dim sNewId
'Check for the bottom of the tree
If IsNull(sId) Then
Exit Sub
End If
sql = "select * from category where parentid=" & sId
Set rs = CurrentDb().OpenRecordset(sql)
Do While Not rs.EOF
sFieldValues = sFieldValues & sId & ";" & rs("categoryid") & ";" & rs("title") & ";"
'Recursive call to check for children
Call LoadCategory(rs("categoryid"))
rs.MoveNext
Loop
If Not rs Is Nothing Then
rs.Close
End If
Set rs = Nothing
End Sub
Active Server Page (Tree View)
Next Access "How To": Calculating Work Days