DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Search Directory
ASP Directory
Xml Directory

How to populate a dynamic dropdown

Author: Asif

Use this small code to populate a dropdown from a database tabel in an ASP page. This Sub Routine will check for selected Record and mark as Selected.

Option Explicit

' Let's populate a dropdown with the User Names from 
' UserInfo table where UserID 3 should be selected 
' in the dropdown

Dim SelectedUserID
SelecteduserID = 3

' We will make a call to Sub Routine PopulateDropDown 
' which will select all users from UserInfo table and 
' populate a dropdown. This sub routine will also check 
' for selected user and marked as SELECTED

Call PopulateDropDown( SelectedUserID )

' *********************************
' Populate Drop Down Sub Routine
' *********************************
Sub PopulateDropDown(byVal SelectedUserID)
 Dim objConn
 Dim objRS
 Dim strSQL
 Dim UserID
 Dim UserName
 Const adOpenForwardOnly = 0
 Const adLockReadOnly  = 1
 Set objConn = Server.CreateObject("ADODB.Connection")
 Set objRS  = Server.CreateObject("ADODB.Recordset")

 objConn.Open "DSN=MyDSN;UID=Test;PWD=Test"

 strSQL = "SELECT UserID, UserName FROM UserInfo"
 objRS.Open strSQL, objConn, adOpenForwardOnly, adLockReadOnly 
 Response.Write "<SELECT Name=""UserID"">"
 Response.Write "<OPTION Value=""""></OPTION>"
 ' Loop through the recordset and populate the dropdown
 Do Until objRS.EOF = True 
  UserID  = objRS("UserID").Value 
  UserName = objRS("UserName").Value 
  If UserID = SelectedUserID  Then
   Response.Write "<OPTION Value=""" & UserID & """ SELECTED>"
   Response.Write UserName 
   Response.Write "</OPTION>"
   Response.Write "<OPTION Value=""" & UserID & """>"
   Response.Write UserName 
   Response.Write "</OPTION>"
  End If
 Response.Write "</SELECT>"
 Set objRS = Nothing
 Set objConn = Nothing
End Sub

Here is the output of above code.

<SELECT Name="UserID">
<OPTION Value=""></OPTION>
<OPTION Value="1">Mike</OPTION>
<OPTION Value="2">Joe</OPTION>
<OPTION Value="4">Robert</OPTION>

Have Questions? Discuss this topic in Dev Forum


Disclaimer - Privacy
© 2002-2016