Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Intermediate
Aug 26, 1999

Link List Contents to Listindex in Another List

I recently needed to create two listboxes, where the items displayed in the second listbox depend upon the item selected in the first listbox. After seeing the amount of code it took to do this using standard arrays, I came up with a better solution using array functions that reduced the amount of code by half. As an added benefit, using array functions makes it easy to add items to the listboxes-you don't need to modify any array dimensions, which makes the code much less error-prone. For example, to add the item "Candy Bars" to the first listbox, simply insert the subarray into the main array; nothing else is needed:

Array(3, "Candy Bars", "Milky Way", "Baby Ruth", _
	"Almond Joy")

The code uses one subarray for each item in the first listbox. The elements of each subarray are the number of items for the second listbox, followed by the item for the first listbox, followed by the items for the second listbox.

To test the code, start a Standard EXE project and put two listboxes on the form, keeping the default names of List1 and List2:

Option Explicit

Private varArray As Variant
Private varSubArray As Variant

Private Sub Form_Initialize()
	varArray = Array(Array(4, "Fruit", "Apples", _
		"Oranges", "Peaches", "Pears"), Array(5, _
		"Vegetables", "Peas", "Beans", "Corn", _
		"Beets", "Onions"), Array(3, _
		"Dairy Products", "Milk", "Cream", _
End Sub

Private Sub Form_Load()
	Dim intIndex1 As Integer
	With List1
		For intIndex1 = 0 To UBound(varArray)
			varSubArray = varArray(intIndex1)
			.AddItem varSubArray(1)
		Next intIndex1
		.ListIndex = 0
	End With
End Sub

Private Sub List1_Click()
	Dim intIndex2 As Integer
	With List2
		varSubArray = varArray(List1.ListIndex)
		For intIndex2 = 0 To varSubArray(0) - 1
			.AddItem varSubArray(intIndex2 + 2)
		Next intIndex2
		.ListIndex = 0
	End With
End Sub

This code works with VB5 and VB6, and should work with any version that supports the Array function.

Paul Carlson
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date