By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,950 Members | 986 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,950 IT Pros & Developers. It's quick & easy.

Adding all items to a list box with each item separated by a ;

P: 1
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 ;
Dec 17 '15 #1
Share this Question
Share on Google+
2 Replies

P: 299
I've included some very basic code with comments. Hope this helps!

Expand|Select|Wrap|Line Numbers
  1.         'testString is the string you wish to build which includes the semicolon
  2.         Dim testString As String
  3.         'endInteger is simply the last listbox item index
  4.         Dim endInteger As Integer = ListBox1.Items.Count - 1
  6.         'The for loop creates an integer starting at zero (the first items index), and loops
  7.         'until it reaches endInteger, or the last listbox item index.  We assume that we don't
  8.         'need a semicolon on the last item, hence the need for the If..Else statement.  If we are
  9.         'on the last item, do not include a semicolon.
  10.         For i As Integer = 0 To endInteger
  11.             If i <> endInteger Then
  12.                 testString += ListBox1.Items(i) & ";"
  13.             Else
  14.                 testString += ListBox1.Items(i)
  15.             End If
  16.         Next
Dec 21 '15 #2

P: 82
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.

Expand|Select|Wrap|Line Numbers
  1.         Dim SomeString As String = ""
  3.         For i As Integer = 0 To ListBox1.Items.Count - 1
  4.             SomeString &= ListBox1.Items(i).ToString
  5.             If i < ListBox1.Items.Count - 1 Then SomeString &= ";"
  6.         Next
Dec 28 '15 #3

Post your reply

Sign in to post your reply or Sign up for a free account.