I have a listbox that the user can add to through a textbox. I would like to string all items in the listbox into a single variable separated by a ;
Adding all items to a list box with each item separated by a ;
Collapse
X
-
I've included some very basic code with comments. Hope this helps!
Code:'testString is the string you wish to build which includes the semicolon Dim testString As String 'endInteger is simply the last listbox item index Dim endInteger As Integer = ListBox1.Items.Count - 1 'The for loop creates an integer starting at zero (the first items index), and loops 'until it reaches endInteger, or the last listbox item index. We assume that we don't 'need a semicolon on the last item, hence the need for the If..Else statement. If we are 'on the last item, do not include a semicolon. For i As Integer = 0 To endInteger If i <> endInteger Then testString += ListBox1.Items(i) & ";" Else testString += ListBox1.Items(i) End If Next -
Use a For Next loop to iterate through the ListBox items and append them to a String. If it is not the last item then append a semi-colon to it too.
As a side note, ListBox Items are Object types and need to be converted to String types. You can use the CStr() function or the ToString method to do that.
Also, you should always use the & character when joining Strings together instead of the + character.
Code:Dim SomeString As String = "" For i As Integer = 0 To ListBox1.Items.Count - 1 SomeString &= ListBox1.Items(i).ToString If i < ListBox1.Items.Count - 1 Then SomeString &= ";" NextComment
Comment