[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 224
  • Last Modified:

Assigning selected list box values to an array

I am trying to read the selected items from a list box into an array.  The code I have is:

    Public Sub Array_lstCells()
        Dim a As Integer = lstCells.SelectedItems.Count
        Dim arr_lstCells(a)
        Dim i As Integer = 0

        For Each SelectedItem In lstCells.SelectedItems
            arr_lstCells(i) = lstCells.SelectedItems.Item(i)
            i = i + 1
        Next
    End Sub

I would also like to display these values in a message box just to make sure it is capturing everything properly.
0
stewdaddy
Asked:
stewdaddy
  • 2
  • 2
1 Solution
 
Jaime OlivaresCommented:
try with the following:

Public Sub Array_lstCells()
        Dim a As Integer = lstCells.SelectedItems.Count
        Dim arr_lstCells(a)
        Dim i As Integer = 0
        Dim sb as New StringBuilder()

        For Each sel as Object In lstCells.SelectedItems
            arr_lstCells(i) = lstCells.SelectedItems.Item(i)
            i = i + 1
            sb.Append(sel.ToString() & vbCrLf)
        Next
        MessageBox.Show(sb.ToString())
    End Sub
0
 
stewdaddyAuthor Commented:
I never used the StringBuilder object before, so I did a little research and apparently I have to add the line:
Imports System.Text
However, when I added this, "Imports" becomes underlined and it says there is a syntax error.  Any advice?
0
 
Jaime OlivaresCommented:
yes, you need System.Text, but it should work. StringBuilder allows you faster string concatenating, but if you want to try with pure strings:

Public Sub Array_lstCells()
        Dim a As Integer = lstCells.SelectedItems.Count
        Dim arr_lstCells(a)
        Dim i As Integer = 0
        Dim sb as String = ""

        For Each sel as Object In lstCells.SelectedItems
            arr_lstCells(i) = lstCells.SelectedItems.Item(i)
            i = i + 1
            sb = sb & sel.ToString() & vbCrLf
        Next
        MessageBox.Show(sb)
    End Sub
0
 
stewdaddyAuthor Commented:
This worked great.  Thanks!
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now