To read the article online, visit http://www.4GuysFromRolla.com/webtech/041599-1.shtml

Fill A ComboBox with DB Information
By Joao Vieira


Filling a combo box with results a database query is something that ASP developers need to do often. This script will present an example of how to do just this. It's something every beginner should read and implement!

First you must open the DB, execute your query, and store the results in a recordset. Once we have that recordset, we will make a loop that puts the values into the combo box. For this example, let's say that the table we're querying has the following structure:

Topic
IDNumber
NameText

Here is the script. It's pretty simple to follow along. Happy Programming!

<%
    ' the connection object
    Dim objConnection
    ' the recordset object
    Dim objRecordset

    ' create the Connection object
    Set objConnection = Server.CreateObject("ADODB.Connection")
    ' open the DSN
    objConnection.Open

    ' creates the recordset object
    Set objRecordset = Server.CreateObject("ADODB.Recordset")


    ' SQL String for query     Dim strSQL
    strSQL = "SELECT ID, NAME FROM TOPIC"

    ' execute the SQL statement that you want
    ' The query should return all the data you'll
    ' need in your combo box
    objRecordset.Open strSQL, objConnection
%>

<HTML>
<BODY>
    <FORM ACTION="someurl.asp" METHOD=POST>
        Choose from the combo:
        select name="lstTopic" size="1">
<%
        ' while we don't get the end of DataBase
        Do While Not objRecordset.EOF
            'we put the ID at Value
            ' this value is important to linked tables
%>
            <option VALUE="<%=objRecordset("ID")%>">
                <!-- This is what will appear in the combo box -->
                <%=objRecordset("NAME")%></option>
<%
            ' Move to the next record...
            objRecordset.MoveNext
        Loop ' keep the loop
%>
        </SELECT>
    </FORM>

</BODY>
</HTML>

<%
    ' close the recordset object
    objRecordset.Close

    ' clean the Recordset object
    Set objRecordset = Nothing
%>


Article Information
Article Title: Filling a ComboBox with DB Information
Article Author: Joao Vieira
Published Date: Thursday, April 15, 1999
Article URL: http://www.4GuysFromRolla.com/webtech/041599-1.shtml


Copyright 2017 QuinStreet Inc. All Rights Reserved.
Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers