Grayda
Member
- Joined
- May 20, 2010
- Messages
- 16
- Programming Experience
- 10+
Hi, I was originally going to ask this question, but I did a little poking around and came across the answer myself. Because I couldn't find the answer anywhere else, I thought I'd post it here for others to use.
I was writing a program that would save the contents of a listbox to a database and wanted to reload the users' choices when the opened up that particular row again. My first thought was to do it with two for loops, just as I used to do in VB6, but I thought there must be a better way to do it. And there was. Sort of. It basically involves using the SelectedObjectCollection class.
For this demo, you'll need a listbox called Listbox1. Set selection mode to something other than "One" or else it won't work as expected
When you run this code, "One", "Two" and "Four" should be selected.
I tried to work out a way to get rid of the For loop, but SelectedObjectCollection doesn't have an AddRange, only an Add. If you have an improvement, let me know.
Of course selItems doesn't have to be a manually created array, it can be something grabbed from the database. As long as you can convert it to an array, it should work fine.
I was writing a program that would save the contents of a listbox to a database and wanted to reload the users' choices when the opened up that particular row again. My first thought was to do it with two for loops, just as I used to do in VB6, but I thought there must be a better way to do it. And there was. Sort of. It basically involves using the SelectedObjectCollection class.
For this demo, you'll need a listbox called Listbox1. Set selection mode to something other than "One" or else it won't work as expected
VB.NET:
Dim items(0 To 3) As String
items(0) = "One"
items(1) = "Two"
items(2) = "Three"
items(3) = "Four"
ListBox1.Items.AddRange(items)
Dim selItems(0 To 2) As String
selItems(0) = "Four"
selItems(1) = "Two"
selItems(2) = "One"
Dim selection As New Windows.Forms.ListBox.SelectedObjectCollection(ListBox1)
For i = 0 To selItems.Length - 1
selection.Add(selItems(i))
Next
When you run this code, "One", "Two" and "Four" should be selected.
I tried to work out a way to get rid of the For loop, but SelectedObjectCollection doesn't have an AddRange, only an Add. If you have an improvement, let me know.
Of course selItems doesn't have to be a manually created array, it can be something grabbed from the database. As long as you can convert it to an array, it should work fine.