| Answer: |
The answer to this FAQ comes from Eric Hewitt.
Populating a drop down box from a database isn't as hard as one would think. First, you should have a database — for this FAQ, I'll be using a sample database that I made up that has a DSN created named states and a table called tblStates with two fields: fldAbbr and fldFull. fldAbbr contains the abbreviation name of the state (like CA) while fldFull contains the state's full name (like California). (For information on creating a DSN, be sure to read: Setting Up a System DSN on Windows 98/NT.)
Here's my example page:
<% Option Explicit
'declare our variables Dim conn,sql,rs
'connect to db and open our query Set conn=Server.CreateObject("ADODB.Connection") conn.open "DSN=states"
sql="SELECT * FROM tblStates ORDER BY fldFull"
Set rs=conn.execute(sql) %>
<html> <head> <title> Database Drop Down Menu </title> </head> <body> <form action="form2.asp" method=post> <select name="mystates"> <% Do While Not rs.eof Response.Write("<option value=""" & rs("fldAbbr") & """>" & _ rs("fldFull") & "</option>") rs.movenext Loop
conn.close Set conn=Nothing Set rs=Nothing %> </select> </form> </body> </html>
|
As you can see, this doesn't require a lot of code! To get the value of the selected drop down box item, just have the form2.asp page include the code: <% myvariable = Request.Form("mystates") %>, and it's that easy!
Another method that you can use to populate an HTML dropdown list is through the ADO method GetString. This provides faster performance and more compact code than the example above. (The example above was provided to show a simple, basic way to place database results in an HTML dropdown list.) To learn how to do this, be sure to read: Displaying Listboxes and Hyperlinks with GetString.
Happy Programming!
|