When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
Related Web Technologies
User Tips!
Coding Tips

Sample Chapters
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Stump the SQL Guru!
XML Info
Author an Article

The 4 Guys Present: ASPFAQs.com

Jump to a FAQ
Enter FAQ #:
..or see our 10 Most Viewed FAQs.

4GuysFromRolla.com : ASP FAQS : Databases, General


How can I use RecordSet.GetString to create a drop down list? How about other more complex output using GetString?

[Print this FAQ]

Answer: The GetString method of ADODB.RecordSet has a few problems and could certainly use an update, but with a bit of care and perhaps a few SQL "tricks" it can be a really valuable tool.

The syntax for GetString is as follows

stringValue = rsObject.GetString( format, numRows, columnDelimiter, rowDelimiter, ifNull )

where rsObject is an ADODB.RecordSet object that has been opened and currently contains one or more records. (Well, GetString still works, even if the recordset is empty, but the output isn't very interesting.)

There is only one valid value for format, and it is an option argument in any case, so we ignore it. You can also omit numRows if you want to convert all the records in the RecordSet into your output string (the normal case). And the last argument, ifNull, is simply a string that is substituted for any null values found. Most of the time you won't have null values, so you can probably ignore this argument, as well.

Which leaves the only two important arguments:

The columnDelimiter is pretty straight forward. When the output string is created, one instance of whatever string you pass for this argument is placed after each field (column) value of every row except after the last field of each row.

The rowDelimiter is what is placed after the last field of each row.

And therein lies a bug. Suppose you use

<TABLE Border=1>
<% = Response.Write rs.GetString( , , "</TD><TD>", "</TD></TR><TR>", ) %>

Oops! You will have a bug! Your HTML output will look like this (not as nicely formatted, but otherwise the same):

<TABLE Border=1>
    <TD>row1, field1 value</TD>
    <TD>row1, field2 value</TD>
    <TD>row2, field1 value</TD>
    <TD>row2, field2 value</TD>

See it? Because the row delimiter follows every row, you get the extra <TR> tag on the end, thus invalidating the entire table!

So, now that we are aware of that bug, let's fix it. And, at the same time, show how we can use GetString to create a drop-down list (a <SELECT> control) quickly and easily.

Set RS = conn.Execute("SELECT theValue,theText FROM selectOptionsTable ORDER BY theText")

optSuffix = "</OPTION>" & vbNewLine
valPrefix = "<OPTION Value='"
valSuffix = "'>"
opts = RS.GetString( , , valSuffix, optSuffix & valPrefix, "--error--" )
' Next line is the key to it!
opts = valPrefix & Left( opts, Len(opts)-Len(valPrefix) )

Response.Write "<SELECT ...>" & vbNewLine & opts "</SELECT>"

As noted, the important key is the "fixup" line that is needed after you do the GetString. But before we get there, the other key is that I have prepared myself by specifying valPrefix and valSuffix separately.

Since we use the RowDelimiter to start the next option line (by tacking on that valPrefix), we have to remove the last one of those prefixes, which I do by "shortening" the result of GetString by the appropriate amount! And I purposely used the names shown so that it's easy to lop off the extra stuff put there by GetString. Not to mention making the code more readable. Naturally, we then have to add the prefix to the set of options, else the first one would not have is <OPTION Value=' in front of it!

Incidentally, if you wanted to apply the principles of this to create a proper table--that is, if you want to fix the example that I showed at the top of this page--you could follow the same general code outline and do something like this:

Set RS = conn.Execute("SELECT * FROM table")

tdSuffix = "</TD>" & vbNewLine & "<TD>
trPrefix = "<TR>" & vbNewLine & "<TD>"
trSuffix = "</TD>" & vbNewLine & "</TR>" & vbNewLine
opts = RS.GetString( , , tdSuffix, trSuffix & trPrefix, "--error--" )
' Next line is the key to it!
opts = Left( opts, Len(opts)-Len(trPrefix) )

Response.Write "<TABLE Border=1 CellPadding=5>" & vbNewLine
Response.Write trPrefix & opts
Response.Write "</TABLE>" & vbNewLine

Check it out! Try it yourself!

Another way!

Finally, there's another completely different way to do this!

SQL = "SELECT '<OPTION Value=''',value,'''>',text,'</OPTION>' FROM table ORDER BY text"
Set RS = conn.Execute(SQL)
Response.Write "<SELECT>" & vbNewLine & RS.GetString(,,"",vbNewLine) & "</SELECT>"

See it? You can get constant values from a query! It is perfectly legal and is, in fact, done all the time when using SQL "standalone" to build reports, etc. So here we simply put in constants that create the stuff to surround the option values, use nothing at all for the column delimiter, and presto! It all comes out pretty.

And we got rid of the "bug" in GetString by not having any row delimiter (except the NewLine). Voila!

You could even take this one step further in Access:

SQL = "SELECT '<OPTION Value=''' & value & '''>' & text & '</OPTION>' FROM table ORDER BY text"
Set RS = conn.Execute(SQL)
Response.Write "<SELECT>" & vbNewLine & RS.GetString(,,"",vbNewLine) & "</SELECT>"

Look at that! The query now returns only one field per record in the RecordSet! You might be able to find other uses for this trick.

NOTE: You can do this same trick with other databases, but not all support the & character for concatenating strings. Most will require you to call the Concat function, which isn't hard but the code will then look ugly.

FURTHER NOTE: The disadvantage of this last scheme is that you are returning more data from the DB when you run your query. If you are only returning dozens of records, the extra data overhead is negligible, especially when compared with time that might be spent in VBScript "prettying" things up. If, however, you might return hundreds or thousands of records (to, perhaps, filter or otherwise work with), then this might produce more overhead than it is worth.

For more information on GetString be sure to check out these 4Guys articles:
-- Displaying Hyperlinks and Listboxes with GetString
-- Speeding Up ASP by Using GetString

Addendum! Preselecting one <OPTION> when using GetString

Well, if I had realized that Scott had those other resources up on 4GuysFromRolla.com, I probably wouldn't have posted this FAQ. But since I did...

As soon as I posted it I got a great question:

"How do I pre-select an OPTION in a GetString-generated list of options?"

Turns out, the answer is pretty easy. But maybe not obvious.

I assume in the following code that the variable preselectValue contains the value that matches the option you want to have selected when the <SELECT> list appears. So you just do:

opts = RS.GetString( ... ) ' same code as above...
opts = valPrefix & Left( opts, Len(opts) - Len(valPrefix) ) ' ...and more of the same

' and here's the trick!
temp = "Value='" & preselectValue & "'"
opts = Replace( opts, temp, temp & " SELECTED", 1, -1, vbTextCompare )

Presto. See why it works?

Suppose you have this for the "opts" string:

"<OPTION Value='one'>First</OPTION><OPTION Value='two'>Second</OPTION>"

Then you do

opts = Replace( opts, "Value='two'", "Value='two' SELECTED" )

(the vbTextCompare is optional, put there if you want to match an option value regardless of upper/lower case).

And now you have this for opts:

"<OPTION Value='one'>First</OPTION><OPTION Value='two' SELECTED>Second</OPTION>"

So you can still use the speedy GetString methodology even if you need an option preselected.

FAQ posted by Bill Wilkinson at 1/16/2001 7:56:41 PM to the Databases, General category. This FAQ has been viewed 59,771 times.

Do you have a FAQ you'd like to suggest? Suggestions? Comments? If so, send it in! Also, if you'd like to be a FAQ Admin (creating/editing FAQs), let me know! If you are looking for other FAQs, be sure to check out the 4Guys FAQ and Commonly Asked Messageboard Questions!

Most Viewed FAQs:

1.) How can I format numbers and date/times using ASP.NET? For example, I want to format a number as a currency. (761643 views)
2.) I am using Access and getting a 80004005 error (or a [Microsoft][ODBC Microsoft Access Driver] The Microsoft Jet database engine cannot open the file '(unknown)' error) when trying to open a connection! How can I fix this problem? (207777 views)
3.) How can I convert a Recordset into an array? Also, how can I convert an array into a Recordset? (202549 views)
4.) How can I quickly sort a VBScript array? (196039 views)
5.) How can I find out if a record already exists in a database? If it doesn't, I want to add it. (156019 views)
6.) How do I display data on a web page using arrays instead of Do...While...MoveNext...???... (152331 views)
7.) When I get a list of all files in a directory via the FileSystemObject, they aren't ordered in any reasonable way. How can I sort the files by name? Or by size? Or by date created? Or... (140381 views)
8.) For session variables to work, must the Web visitor have cookies enabled? (110162 views)
9.) Can I send emails without using CDONTS? (107083 views)
10.) How can I take the result of a SELECT...MULTIPLE or a group of same-named checkboxes and turn it into a query? That is, if the user selects 3 answers, how can I construct a query that looks for all 3? (106308 views)
Last computed at 9/17/2007 3:22:00 AM

ASP.NET [1.x] [2.0] | ASPFAQs.com | Advertise | Feedback | Author an Article