PipBoy
PipBoy

Reputation: 1137

Convert list (of string) from datareader to string

I've captured some data from a datareader into a list and now I'm wondering what's the best way to put these out into strings.

The requirement I have is I need to grab field names from a table and then out put these as headings on a page.

 objConn = New SqlConnection(strConnection)
    objConn.Open()
    objCmd = New SqlCommand(strSQL, objConn)
    rsData = objCmd.ExecuteReader(0)

    If rsData.HasRows Then

        Do While (rsData.Read())

            Dim SubjectNames As New List(Of String)

            SubjectNames.Add(rsData.GetString("subject"))



        Loop

            SubjectList = SubjectNames.ToArray

Now I was thinking ToArray and was wondering how then to output all of the list entries into strings that I can then use later on.

It's also prudent to note that I'm doing this all inline as the CMS I have to use doesn't allow any code behind.

Upvotes: 0

Views: 1025

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460028

If i understand you correctly you don't know how to convert a List(Of String) to a string. You can use String.Join and specify which string you want to use to join the words:

Dim SubjectNames As New List(Of String)
Do While (rsData.Read())
    SubjectNames.Add(rsData.GetString("subject"))
Loop

Dim headers As String = String.Join(", ",  SubjectNames)

Note that i've moved the declaration of the list outside of the loop because otherwise you would always create a new list for every record.

Edit: So you don't know how to access elements in a List or Array.

Elements in a List(Of String) or String() are already individual strings. You access each element via indexer. For example: Dim firstSubject = SubjectNames(0) or via Linq: firstSubject = SubjectNames.First(). For the 10th element: Dim subject10 = SubjectNames(9) since indexes are zero based.

MSDN: Arrays in Visual Basic

Upvotes: 1

Related Questions