While working on an app I found myself in an unexpected situation when a piece of code that had been working fine began to throw an
OutOfBoundException. After a bit of debugging I found that the culprit was the length of an array passed to the
AddRow method of a ListBox instance.
It seems that when we call this ListBox method passing an Array, all the array’s contents are passed by value and not by reference. This means that if the array has a few items there is no problem passing it around. But if, as in this case, the array’s content is suddenly a lot bigger then this fills the stack causing the
OutOfBoundsException. The mistake is that using:
MyListBoxInstance.AddRow( MyBigArray )
Adds every item in the array for each ListBox Column, while for adding all the entries as differente rows in the ListBox we have to iterate over the array, adding every item to the ListBox instance one at a time:
For Each itemString as String in MyBigArray MyListBoxInstance.AddRow( itemString ) Next
This means using just two more lines of code, but it’s much better and preferable when we don’t know in advance the number of items that could end up in our intermediate array.
This approach works both if the array has few items in it or when it has to deal with a large number of items; for example this could be the situation when downloading content from an Internet API, web service, or when dealing with information from a database query.
All in all… there is not an included method that allows passing an Array just to add all the items as new rows for the ListBox. Maybe that is a good point for a class Extension. Inside a Module, add a new Method with the following signature:
- Method Name: addRows
- Parameters: Extends l as ListBox, byref data() as string
And write the following code in the associated Code Editor:
For Each item As String In data l.AddRow item Next
Now it will be simpler adding an array of strings to your ListBoxes from the project. Of course, you can tweak the code in the method class extension so it works with other kind of Arrays.