Help with selecting multiple rows from a listbox and assigning values to a variable using VB.NET

vcharles
vcharles used Ask the Experts™
on
Hi,

How do you select multiple rows from a listbox and assigning values to a variable using VB.NET?  For example if I select
House, Garage, Car from the listbox, would like to select a string variable s = House,Garage,Car.

Thanks,

Victor
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Ryan ChongSoftware Team Lead

Commented:
try:
Dim items As New List(Of String)
        For Each itm In ListBox1.SelectedItems
            items.Add(itm.ToString())
        Next
        Dim rst As String
        rst = String.Join(",", items.ToArray)
        MessageBox.Show(rst)

Open in new window

Retired
Distinguished Expert 2017
Commented:
Hi Victor;

The following code snippet should do what you need.
'' This linq query will iterate through the selected items in the 
'' ListBox control and build a comma seperated string of the selected values
'' The variable acc is the string that is being built and item is the next item in the ListBox 
Dim s As String = (From r In ListBox1.SelectedItems
                   Select r).Aggregate(Function(acc As String, item As String) acc & ", " & item)

Open in new window

Author

Commented:
Thank You. I will get back to you.
Expert Spotlight: Joe Anderson (DatabaseMX)

We’ve posted a new Expert Spotlight!  Joe Anderson (DatabaseMX) has been on Experts Exchange since 2006. Learn more about this database architect, guitar aficionado, and Microsoft MVP.

Author

Commented:
Hi Fernando,

Your solution works, is there a way to select multiple rows from the listbox without pressing the ctrl key?

Thanks,

Victor

Author

Commented:
Thank You.

Author

Commented:
Please disregard question from last post.
Fernando SotoRetired
Distinguished Expert 2017

Commented:
Not a problem Victor, glad to help.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start Today