Navigation

Search

Categories

On this page

Creating an Array or String from Database Records

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 112
This Year: 50
This Month: 0
This Week: 0
Comments: 0

Sign In

 Thursday, June 07, 2007
Thursday, June 07, 2007 10:23:55 AM (Eastern Standard Time, UTC-05:00) ( )

I've been working on a project which inolved a lot of javascript and one requirement was to grab a list of industry values and their primary keys, place them into an array or string and then return those back to my javascript function.   In this first example I use the StringBuilder() method which I guess from user feedback is much more efficient than creating a ArrayList object.

<script runat="server">
Sub Page_Load()
Dim strSQLConn As SqlConnection
Dim strSqlText As String
Dim cmd As SqlCommand
'Dim myList As New ArrayList
Dim dr As SqlDataReader
Dim count As Integer
Dim mySB As New StringBuilder()

strSQLConn = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
strSqlText = "getIndustries"
cmd = New SqlCommand(strSqlText, strSQLConn)
cmd.CommandType = CommandType.StoredProcedure

Try
strSQLConn.Open()
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)

With dr
If dr.HasRows Then
While dr.Read
mySB.Append("{")
mySB.Append(dr.GetInt32(0))
mySB.Append("#")
mySB.Append(dr.GetString(1))
mySB.Append("}")
count += 1
End While
End If
End With

Finally
dr.Close()
strSQLConn.Close()
End Try

Dim strResults As String
strResults = mySB.ToString().TrimEnd(",".ToCharArray())
Response.Write(strResults)
End Sub

In this second example, I do the identical thing except that I use an ArrayList

<script runat="server">
Sub Page_Load()
Dim strSQLConn As SqlConnection
Dim strSqlText As String
Dim cmd As SqlCommand
Dim myList As New ArrayList
Dim dr As SqlDataReader
Dim count As Integer

strSQLConn = New SqlConnection(ConfigurationSettings.AppSettings("CorpLibConnectionStringCurr"))
strSqlText = "getCompanyNames"
cmd = New SqlCommand(strSqlText, strSQLConn)
cmd.CommandType = CommandType.StoredProcedure

Try
strSQLConn.Open()
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)

With dr
If .HasRows Then
While .Read
myList.Add("{")
myList.Add(.GetInt32(0))
myList.Add("#")
myList.Add(.GetString(1))
myList.Add("}")
count += 1
End While
End If
End With

Finally
dr.Close()
strSQLConn.Close()
End Try

Dim i As Integer

For i = 0 To myList.Count - 1
Response.Write(myList(i))
Next

End Sub


</script>