Antonio Mira of Columbus, Ohio, writes in with this question: "I have a list box that I have bound to a data set. The list box displays the values fine. I have used one column from the dataset as the display member and another column as the value. I have enabled the list box to select multiple values at a time. What is the best way to iterate through the values selected? I need to build a string of the values (not the displayed options) selected."
As I understand the question, Antonio wants to do something like what is shown in Figure 1 [2]: get the values that are selected (in the figure, I show both the displayed value and the list value, which is the state abbreviation).
At first glance, how difficult can that be?
The problem here is that the MSDN documentation in Visual Studio for the ListBox control leaves you dangling. It mentions the important player (the ListBox.SelectedObjectCollection) but leaves out some important clues about how to work with it. In short, there doesn’t seem to be a good example in MSDN.
A few minutes with Google revealed a C# solution, which I’ve translated into Visual Basic (see Figure 2 [3]).
In Figure 2 [4], the Form1_Load subroutine is used to simply load data into the ListBox. There is nothing particularly interesting in that subroutine unless you didn’t know that you could programmatically create a dataset and datatable. To keep my example simple, I opted to create the dataset in code, without connecting to an actual database.
All the important action takes place in the btnShow_Click subroutine. There are two main points to keep in mind to access the items in the listbox:
After you have the SelectedObjectCollection object, you can simply iterate over it, picking out each row. Within the row, you access the first and second elements (identified as dr(0) and dr(1)). After you have those values, you have access to both the displayed value (the ListBox.DisplayMember) and the backing value (the ListBox.ValueMember).
So how hard was that? Well, apparently other folks are having some problems getting this figured out. Go to the URL that I show in the btnShow_Click subroutine (which is the reference I used from Google). After you see the C# example, (message 2 on that page), read the third message.
Links:
[1] http://systeminetwork.com/author/craig-pelkie
[2] http://pentontech.com/IBMContent/Images/article/56824_50564_listBox_F01.jpg
[3] http://pentontech.com/IBMContent/Documents/article/56824_627_listBox_F02.doc
[4] http://pentontech.com/IBMContent/Documents/article/56824_627_listBox_F02.doc