Loading listbox selected items from a database

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

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.
 
As you're using .NET 4.0, this sort of thing is simple with a little bit of LINQ:
Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            'Get the delimited String from the user settings.
            Dim delimitedValues = My.Settings.ListBox1SelectedIndices

            'Check whether there is a value present.
            If Not String.IsNullOrWhiteSpace(delimitedValues) Then
                'Break up the individual values.
                Dim selectionNumbers = delimitedValues.Split("|"c)

                'Convert the Strings to indexes.
                Dim selectedIndicies = Array.ConvertAll(selectionNumbers, Function(s) CInt(s))

                'Select the corresponding items.
                For Each index In selectedIndicies
                    Me.ListBox1.SelectedIndices.Add(index)
                Next
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString())
        End Try
    End Sub

    Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
        'Get the indexes of the selected items.
        Dim selectedIndices = Me.ListBox1.SelectedIndices.Cast(Of Integer)().ToArray()

        'Convert the indexes to Strings.
        Dim selectionNumbers = Array.ConvertAll(selectedIndices, Function(n) n.ToString())

        'Join the Strings into a single delimited String.
        Dim delimitedValues = String.Join("|", selectionNumbers)

        'Save the delimited String to the user settings.
        My.Settings.ListBox1SelectedIndices = delimitedValues
    End Sub

End Class
or the condensed version:
Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            Dim delimitedValues = My.Settings.ListBox1SelectedIndices

            If Not String.IsNullOrWhiteSpace(delimitedValues) Then
                'Select the same items from the previous session.
                For Each index In Array.ConvertAll(delimitedValues.Split("|"c),
                                                   Function(s) CInt(s))
                    Me.ListBox1.SelectedIndices.Add(index)
                Next
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString())
        End Try
    End Sub

    Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
        'Remember which items were selected for the next session.
        My.Settings.ListBox1SelectedIndices = String.Join("|",
                                                          Array.ConvertAll(Me.ListBox1.SelectedIndices.Cast(Of Integer)().ToArray(),
                                                                           Function(n) n.ToString()))
    End Sub

End Class
One advantage of this code is that it doesn't care what the type of the items is. Because it uses the index of the item rather than the item itself, it will work for any item type.
 
Back
Top