How Do I Bind a Database to a WebFX Combo Box Control?

An often requested feature in Web applications is a drop-down that behaves like a Combo Box in Windows applications. If you start typing in a drop-down in a Windows application, it will preselect an item that starts with all the letters you type in. The drop-down in a Web browser preselects the item that starts with the last letter you typed in. Not very convenient. Fortunately, there are many replacements for the default drop-down available. One of them is the WebFX Combobox. In this snippet, I will demonstrate you how to fill this control with information from a database. I won't be discussing how the control works, and I also won't explain how you can use the advanced features of the control that allows you to add new data. This snippet will simply demonstrate how to generate the client-side code for the drop-down with information from a database.

Prerequisites

Before you start, make sure you download the WebFX Combobox first. Next, unpack the archive and move the files ComboBox.css and ComboBox.js to a folder in your Web site. Next, create a new ASP file called Combobox.asp. You can choose any location for the files you want, but this snippet assumes that all three files are located in the same folder.

You'll also need a database with at least one table that contains the data that you want to add to the drop-down. In this code example, I am using a table called Countries. Each country has an ID (its ISO code) and a Description. The ID is used as the value attribute for each option, while the Description is used as the visible part in the drop-down control. The article assumes that the database is placed in the same folder as well, so be sure to change the path that is passed to Server.MapPath if you decide to move your database.

I am using a list of countries just for demonstration purposes. Since the list of countries isn't likely to change very often, it's probably better to use a static JavaScript file with the code for the countries already aded. Generating the entire JavaScript code from the database everytime the page loads may not be a wise idea in a real-life application, as it causes a lot of performance overhead. For this example however, the country list is just perfect, as it provides enough sample data to test out the functionality of the control.

The Code

The following code demonstrates how to bind the smart Combo Box to a recordset. Please note that I am not responsible or taking credit for the Combo Box control. This article just demonstrates how to use the Combo Box in combinations with a database. Contact WebFX for more information about the Combo Box control.

Simply copy the text below and paste it in the document ComboBox.asp.

<%@ Language=VBScript %>
<% Option Explicit %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
  <title>ComboBox Demo</title>
  <script src="ComboBox.js" type="text/javascript"></script>
</head>

<body>
  <script type="text/javascript">
  dm=new ComboBox("dm")
  dm.add(
  <%
    ' Create Connection object, connection string etc
    Dim MyConnection
    Dim MyConnectionString
    Dim MySQLStatement
    Dim MyRecordset
    MyConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
            "Data Source=" & Server.MapPath("Website.mdb") & _
            ";User Id=admin;Password="

    ' SQL Statement will return a recordset with an ID 
    ' (the ISO code for the country) and the name / description of the Country
    MySQLStatement = "SELECT Country.ID, Country.Description " & _
        "FROM Country ORDER BY Country.Description"

    Set MyConnection = Server.CreateObject("ADODB.Connection")
    MyConnection.Open MyConnectionString

    ' Execute the SQL statement
    Set MyRecordset = MyConnection.Execute(MySQLStatement)

    If Not MyRecordset.EOF Then
    Do While Not MyRecordset.EOF
      ' For each record in the recordset, construct a new ComboBoxItem.
      ' ComboBoxItem is defined in the file ComboBox.js

      Response.Write(vbTab & "new ComboBoxItem('" & _
            MyRecordset.Fields("Description").Value & "', '" & _
            MyRecordset.Fields("ID").Value & "')")

      MyRecordset.MoveNext()

      ' Are there more items? If so, we need to add a comma
      If Not MyRecordset.EOF Then
        Response.Write("," & vbCrLf)
      End If
    Loop 
  End If

  ' Clean Up
  MyRecordset.Close()
  Set MyRecordset = Nothing
  MyConnection.Close()
  Set MyConnection = Nothing
%>
)
</script>
</body>
</html>

Open the page in your browser, click the Combo Box and then type in Net. As soon as you start typing letters, you'll see the list of countries being limited to those starting with the letters you have typed. Once you typed Net, the list will look like this:

The Combox Control with the list limited to those countries starting with Net
Figure 1: The Combobox in action

Live Demo

You can test out a live demo of the example here.

Download Files

Source Code for this Article
(The code download just contains the database and the .asp file. For the code for the ComboxBox, please check out the WebFX site.

Where to Next?

Wonder where to go next? You can read existing comments below or you can post a comment yourself on this article .


Consider making a donation
Please consider making a donation using PayPal. Your donation helps me to pay the bills so I can keep running Imar.Spaanjaars.Com, providing fresh content as often as possible.



Feedback by Other Visitors of Imar.Spaanjaars.Com

On Friday, February 11, 2005 5:30:48 AM Joe Anderson said:
What good is this?  The DHTML control blows up if you put it in a <form> tag....  also can not preselect the value....??? Am I missing something?
On Saturday, February 12, 2005 1:28:17 PM Imar Spaanjaars said:
You cannot directly add it to a form, so it doesn't automatically post its value.

However, the combobox exposes a valcon property which is a normal input box. You can get the selected value from that text box like this:

dm.valcon.value;

So, you could add a function like this:

function GetValue()
{
return dm.valcon.value;
}

and use it like this to get the value:

<input type="button" onclick="alert(GetValue());" value="Click Me" />

You can call the GetValue when the form is posted to copy the selected value to a hidden form field, for example.

Look in the source of ComboBox.js to see more methods and properties you can use.
This snippet was targeted at showing how to add dynamic data to the control; it wasn't meant as an explanation of the control itself. For more details check out the WebFX site.
On Saturday, June 25, 2005 2:46:51 PM Deepak Garg said:
This is a good Example but it is not running after modifying it in JSP.
My Problem is that I want select name from the student list. I want combo Box like 'Gmail -> Compose -> To Combo Box'.
Please send me any example which fulfills my requirements.
On Saturday, June 25, 2005 2:52:55 PM Imar Spaanjaars said:
If it's not working, you probably made a mistake somewhere... ;-)

The example I posted here does work, albeit in ASP. For a JSP solution I suggest you check out a forum.
The functionality you're describing is not offered by the WebFX control so you need to think of anther solution.

Imar
On Thursday, July 14, 2005 3:06:54 PM Mischa said:
Is this an example of Ajax?
On Thursday, July 14, 2005 3:13:03 PM Imar Spaanjaars said:
No, it isn't. AJAX uses communication with the server behind the scenes, while this is a pure client side solution.

It would make for a nice AJAX implementation, though....

Imar
On Monday, July 17, 2006 9:41:34 AM ankit mangal said:
this is good......but i want to show corresponding entries in textboxes when a particular option is chosen from combo box
On Monday, July 17, 2006 2:44:47 PM Imar Spaanjaars said:
Hi Ankit,

What you are looking for is called linked listboxes. Search Google for "linked listbox javascript" and you'll find plenty of useful articles.

Cheers,

Imar
On Tuesday, July 18, 2006 5:12:38 AM lalit pandey said:
hello sir/madam
                       I learn about ASP & ASP.Net so i would like your site & I'm intrested in your website.so i can request to u pls help me learn in ASP & ASP.Net.

Thanks
lalit pandey
On Tuesday, July 18, 2006 8:04:54 AM Imar Spaanjaars said:
Hi lalit,

Thank you for your interest in my site. However, I don't give personal training so I can't help you much.

I suggest you get a few books like Beginning ASP or Beginning ASP.NET from Wrox at http://www.wrox.com/ and get yourself familiair with the concepts.

Cheers,

Imar
On Thursday, October 18, 2007 5:32:13 AM teddy said:
hi im new to C#...

following code to get a database SQL table column and bind it to combo box.....AssetType is the table and AssetTypName is the column to bind to the combo box.....in C# windows application.............

it shows the exception like child list cannot be created ............

<snip Code Vut by Imar </snip>
On Thursday, October 18, 2007 5:56:30 AM Imar Spaanjaars said:
Hi teddy,

How is this related to binding to WebFX, a *web* control?

Try a forum like http://p2p.wrox.com

Imar
On Thursday, August 21, 2008 5:57:49 AM jamal said:
good job
On Friday, August 21, 2009 8:11:52 AM mukut kandar said:
This is good job . After all I want about to fill another webfx control of city against the selected country with scrolling and if it is possible in asp.net 2.0 using c#
On Saturday, August 22, 2009 8:18:36 AM Imar Spaanjaars said:
Hi mukut,

I am not sure I understand what you're asking....

Imar
On Thursday, October 14, 2010 8:24:31 PM Yvonne Akende said:
Help me with the code to make a combo box read from a particular database table in C#. Am creating an application in C# that i want to be getting values from the database instead of typing the values

Talk Back! Comment on Imar.Spaanjaars.Com

I am interested in what you have to say about this article. Feel free to post any comments, remarks or questions you may have about this article. The Talk Back feature is not meant for technical questions that are not directly related to this article. So, a post like "Hey, can you tell me how I can upload files to a MySQL database in PHP?" is likely to be removed. Also spam and unrealistic job offers will be deleted immediately.

When you post a comment, you have to provide your name and the comment. Your e-mail address is optional and you only need to provide it if you want me to contact you. It will not be displayed along with your comment. I got sick and tired of the comment spam I was receiving, so I have protected this page with a simple calculation exercise. This means that if you want to leave a comment, you'll need to complete the calculation before you hit the Post Comment button.

If you want to object to a comment made by another visitor, be sure to contact me and I'll look into it ASAP. Don't forget to mention the page link, or the QuickDocId of the document.

For more information about the Talk Back feature, check out this news item.