A Custom DropDownList Control With Autocomplete for ASP.NET...

This control lets you type in letters to navigate through the items in a dropdownlist and quickly find the item you want to select.


By: John Kilgo Date: May 8, 2004 Download the code.

First, before get into the article and the presentation of code, let me give credit where it is due. This program was originally written in c# by Jonathan Cogley of Thycotic Software LTD. I converted his c# code to vb code. Otherwise, the code, including the javascript, were written by Jonathan. He has kindly given me permission to present this article using his converted code. I have reformatted the javascript, but otherwise it is as he wrote it. Thanks Jonathan!

First, as most of you should know, the default behavior of the ASP.NET dropdownlist control is limited if you want to type in characters to find a specific item in the dropdownlist. The control responds only to the first character you type. For example, if you wanted to find "Brown" in a list of names you would first type the letter 'b'. The default control will take you to the first 'b' in the list. If you then type in 'r' instead of taking you to the first item beginning with 'br', it takes you to the first item beginning with an 'r'. Every character you type will take you to the first item beginning with that character. This behavior is not very useful.

To get the behavior we want we need to override the default behavior and add some javascript to get the results we want. To create a vb based custom control we first create a vb project of type vb class. Create a Class file named KeySortDropDownList.vb, then enter the code shown below. We are creating a class that inherits a dropdownlist from System.Web.UI.WebControls. For ease of use we don't want the user to have to type in capital letters if the select list items begin with a capital letter. In other words we want the process to not be case sensitive. We do this by creating an overridable propery named CaseSensitiveKeySort and setting its value to false. The first part of the code is shown immediately below.

Imports System
Imports System.Web.UI.WebControls

Namespace Thycotic.Web.UI.WebControls

  Public Class KeySortDropDownList
    Inherits DropDownList
    Private Shared functionName As String = "KeySortDropDownList_onkeypress"
    Private _caseSensitiveKeySort As Boolean = False

    Public Overridable Property CaseSensitiveKeySort() As Boolean
      Get
        Return _caseSensitiveKeySort
      End Get
      Set(ByVal Value As Boolean)
        _caseSensitiveKeySort = Value
      End Set
    End Property

Next comes the javascript which does the work to allow autocomplete as we type in multipe characters. The javascript is commented so I won't go into an explanation of how it works. If you have javascript skills you shouldn't have much problem understanding the code. If you are a javascript neophyte, try to read through it and gain an understanding of what it does, or just trust that it works! The javascript is shown below. The reason for the VbCrLf's is so the javascript will render in a readable fashion. Once you run a webform utilizing the control you can do a view source and see how the javascript is rendered.

  Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
      MyBase.OnLoad(e) ' call the base class method
      ' define the client-side script
      Dim script As String
      script = "<script language=" & Chr(34) & "javascript" & Chr(34) & " type=" & Chr(34) & "text/javascript" & Chr(34) & ">" & vbCrLf
      script &= "function " & functionName & " (dropdownlist,caseSensitive) {" & vbCrLf
      script &= " // check the keypressBuffer attribute is defined on the dropdownlist" & vbCrLf
      script &= " var undefined; " & vbCrLf
      script &= " if (dropdownlist.keypressBuffer == undefined) { " & vbCrLf
      script &= " dropdownlist.keypressBuffer = ''; " & vbCrLf
      script &= " } " & vbCrLf
      script &= " // get the key that was pressed " & vbCrLf
      script &= " var key = String.fromCharCode(window.event.keyCode); " & vbCrLf
      script &= " dropdownlist.keypressBuffer += key;" & vbCrLf
      script &= " if (!caseSensitive) {" & vbCrLf
      script &= " // convert buffer to lowercase" & vbCrLf
      script &= " dropdownlist.keypressBuffer = dropdownlist.keypressBuffer.toLowerCase();" & vbCrLf
      script &= " }" & vbCrLf
      script &= " // find if it is the start of any of the options " & vbCrLf
      script &= " var optionsLength = dropdownlist.options.length; " & vbCrLf
      script &= " for (var n=0; n < optionsLength; n++) { " & vbCrLf
      script &= " var optionText = dropdownlist.options[n].text; " & vbCrLf
      script &= " if (!caseSensitive) {" & vbCrLf
      script &= " optionText = optionText.toLowerCase();" & vbCrLf
      script &= " }" & vbCrLf
      script &= " if (optionText.indexOf(dropdownlist.keypressBuffer,0) == 0) { " & vbCrLf
      script &= " dropdownlist.selectedIndex = n; " & vbCrLf
      script &= " return false; // cancel the default behavior since " & vbCrLf
      script &= " // we have selected our own value " & vbCrLf
      script &= " } " & vbCrLf
      script &= " } " & vbCrLf
      script &= " // reset initial key to be inline with default behavior " & vbCrLf
      script &= " dropdownlist.keypressBuffer = key; " & vbCrLf
      script &= " return true; // give default behavior " & vbCrLf
      script &= "} " & vbCrLf
      script &= "</script>"

Lastly we do two things. We must register the javascript on the client. This is so it will show up in the code of a page using this control. Next we add an attribute to pick up the onKeyPress event. This code, and the remainder of the class file is shown below.

      ' register the client-side script block
      Me.Page.RegisterClientScriptBlock(functionName, script) '
      ' add to the onkeypress event
      Me.Attributes.Add("onkeypress", "return " + functionName + "(this," + _caseSensitiveKeySort.ToString().ToLower() + ")")
    End Sub 'OnLoad
  End Class 'KeySortDropDownList
End Namespace 'Thycotic.Web.UI.WebControls

I hope you have learned something about building custom controls in VB. I hope you can use the custom control in some of your applications. To use the control, download the code and create a VB project of type Class. Copy the downloaded code into the project. Press F5 to build the solution. Then create a VB ASP.NET project. Create a webform, or use the default WebForm1.aspx. In design mode open the tool box and right click. Select the 'Add/Remove Items' option. In the resulting dialog box browse to the KeySortDropDownList.dll, press Select and then OK. The control will then be added to the toolbox. Drag the control onto your .aspx file. Manually add some items to the resulting KeySortDropDownList1 (or whatever you renamed it to). Press F5 to build the project. You then should be able to navigate through your select items with autocomplete.

You may run the example program here.
You may download the code here.