Articles   Dev Forums   Personalize   Favorites   Member Login   ASP Hosting      Active Users:  206
DevASP - ASP and XML Articles, Samples, Toturials, Sample Chapters and resources for Developers Wednesday, May 14, 2008
Home
Articles & Samples
ASP Hosting
Dev Search
Dev Forum
Add Your Articles
Add a Listing
Sample Chapters
Directory Feed
Link to US
Contact

Search Directory
Applications
Articles & Samples
Components
Community
Database
Developer Sites
Downloads
Hosting Services
Introduction
Knowledge Base
Sample Chapters
WebCasts

Trusted by over 7 million customers!
ASP Directory
Applications
Articles & Samples
Components
Developer Sites
Knowledge Base
Sample Chapters
WebCasts
XML Directory
Applications
Articles & Samples
Developer Sites
Error, Bugs & Fixes
Downloads
Introduction
Knowledge Base
Sample Chapters
WebCasts


How to Populate Dynamic DropDown

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>"
  Else
   Response.Write "<OPTION Value=""" & UserID & """>"
   Response.Write UserName
   Response.Write "</OPTION>"
  End If
  
 objRS.Movenext
 Loop
 
 Response.Write "</SELECT>"
 
 objRS.Close
 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="3" SELECTED>Asif</OPTION>
<OPTION Value="4">Robert</OPTION>
</SELECT>

Have Questions? Discuss this topic in Dev Forum

DevASP - Privacy - Disclaimer
Copyright © 2008 DevASP.com