I have a for loop which goes like this:
for i = 0 as integer to 100
result &= "Name" & sqldr("name")
re开发者_StackOverflowsult &= "Lastname" & sqldr("lastname")
result &= "dob" & sqldr("dob")
next
The sqldr is the sql datareader (not important here)
I want my end result to be:Name1 = Sam
Lastname1 = Davis
dob1 = 01/01/1966
Name2 =
...
Name3 =
and so on depending on how many records are in the database. How do I make this happen in this for loop?
Well, first of all you should be using a StringBuilder as it is more efficient than concatenating strings.
So the following should yield the expected result (sorry I am or aquainted to C#):
Dim sb as StringBuilder = new StringBuilder() ' that is where I am not so sure
for i = 0 as integer to 100
sb.AppendFormat("Name{0} = {1}", i, sqldr("name")
sb.AppendFormat("Lastname{0} = {1}", i, sqldr("lastname")
sb.AppendFormat("dob{0} = {1}", i, sqldr("dob")
next
result = sb.ToString()
you'll need to do a select before your For loop. The select will get the total number of records returned. Store that number in a variable.
Dim sqlcount as integer = 100 'this should actually be the result of your sql query
for i = 0 as integer to sqlcount
result &= "Name" & sqldr("name")
result &= "Lastname" & sqldr("lastname")
result &= "dob" & sqldr("dob")
i = i + 1
next
This will do it:
for i = 0 as integer to 100
result &= "ApplicantName" & i.ToString() & " = " & sqldr("name")
result &= "Lastname" & i.ToString() & " = " sqldr("lastname")
result &= "dob" & i.ToString() & " = " sqldr("dob") & "\n\n"
next
But, for better performance, you should be using string.Format and StringBuilder:
Dim sb as StringBuilder = new StringBuilder()
for i = 0 as Integer to 100
sb.Append(String.Format("ApplicantName{0} = {1}", i, sqldr("name"))
sb.Append(String.Format("Lastname{0} = {1}", i, sqldr("lastname"))
sb.Append(String.Format("dob{0} = {1}\n\n", i, sqldr("dob"))
next
Dim result as String = sb.ToString()
StringBuilder also has an AppendFormat overload, that makes this even easier:
Dim sb as StringBuilder = new StringBuilder()
for i = 0 as Integer to 100
sb.AppendFormat("ApplicantName{0} = {1}", i, sqldr("name")
sb.AppendFormat("Lastname{0} = {1}", i, sqldr("lastname")
sb.AppendFormat("dob{0} = {1}\n\n", i, sqldr("dob")
next
Dim result as String = sb.ToString()
精彩评论