Odd problem populating a list box

porksmash

New member
Joined
Jul 3, 2008
Messages
3
Programming Experience
1-3
Does anyone see any reason why this code would not work? I expect the list box to be unchanged after this runs, but instead the box is empty. The add range declaration specifically says it works with a listbox.objectcollection type, and I know the backup variable contains all the data because I can see it with colListBackup.Item(x), but the AddRange is just not working at all like I expect.

VB.NET:
Dim colListBackup As ListBox.ObjectCollection

colListBackup = lstCameras.Items
lstCameras.Items.Clear()
lstCameras.Items.AddRange(colListBackup)
 
Firstly you are just using two variables here referencing the same collection, calling Clear method from either of these will clear that single collection. Secondly the ListBox.ObjectCollection is closely tied to a Listbox instance (check its constructor) so using any other array/collection is better suited for intermediary storage.

Example with an array:
VB.NET:
Dim backup(Me.ListBox1.Items.Count - 1) As Object
ListBox1.Items.CopyTo(backup, 0)
ListBox1.Items.Clear()
ListBox1.Items.AddRange(backup)
Same with an ArrayList collection:
VB.NET:
Dim backup As New ArrayList
backup.AddRange(ListBox1.Items)
ListBox1.Items.Clear()
ListBox1.Items.AddRange(backup.ToArray)
 
Back
Top