devxlogo

Link List Contents to Listindex in Another List

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 ExplicitPrivate varArray As VariantPrivate varSubArray As VariantPrivate 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", _		"Butter"))End SubPrivate 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 WithEnd SubPrivate Sub List1_Click()	Dim intIndex2 As Integer	With List2		varSubArray = varArray(List1.ListIndex)		.Clear		For intIndex2 = 0 To varSubArray(0) - 1			.AddItem varSubArray(intIndex2 + 2)		Next intIndex2		.ListIndex = 0		.Refresh	End WithEnd Sub

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

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist