Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

DropDownWithAutoComplete

0.00/5 (No votes)
25 Jun 2008 1  
The Custom Control shows up a list item in the dropdown as it is typed.
DropDownWithAutoComplete

Introduction

The custom DropDownWithAutoComplete feature shows up a list item in the dropdown as it is typed. It is really helpful when there are a number of items in the dropdown list and the user needs to find a particular item in it. Instead of scrolling and looking for the desired item, the custom DropDownWithAutoComplete allows a user to click on the dropdown list and type the item to look for. As the starting letters of the item are typed, the item that matches the typed letters gets highlighted. Once the desired item is reached, the user can then click on the item to select it.

The user can also set a property to set the first item in the list to be 'Select'. This otherwise would have required inserting an item in the datasource.

Background

While working on one of my projects, it came up as a requirement that in a dropdown list which contains more that 20 items, we had to use some feature that allowed a user to type the name of the item she or he is looking for and consequently that item should get highlighted in the list. This would have helped in looking for and selecting an item particularly when the dropdown contains a number of items.

The feature to set the first item as 'Select' can be used optionally by merely setting up a property.

Using the Code

The code has a single class CustomDropDown that inherits from DropDownList. The procedures and properties are explained below.

The FirstElementSelect property is of type Boolean and sets/returns a value indicating whether the first item in the list will be a Select or not.

Public Property FirstElementSelect() As Boolean
    Get
        Return _IsFirstElementSelect
    End Get
    Set(ByVal value As Boolean)
        _IsFirstElementSelect = value
    End Set
End Property

In the oninit function, i.e. when the controls are initialized, attributes are added to onkeypress and onblur event of the custom DropDownWithAutoComplete.

Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
        Me.Attributes.Add("onkeypress", "return AutoComplete(this);")
        Me.Attributes.Add("onblur", "return Reset(this);")
        MyBase.OnInit(e)
End Sub

The Render function used renders JavaScript to an ASP.NET dropdownlist control's output stream.

Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
            Dim strScript As String = "<script></script>"
            writer.WriteLine(strScript)

            Dim strScript1 As String = "<script></script>"
            writer.WriteLine(strScript1)

            MyBase.Render(writer)
        End Sub

The Prerender event checks the boolean property FirstElementSelect. If set to true, an item 'Select' will be inserted to the existing list of items. This event is handled just before the control is rendered, so by the time all the listitems would have been added to the custom DropDownlist.

Private Sub Class1_PreRender(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles Me.PreRender
            If FirstElementSelect = True Then
                If Not (Me.Items.Contains(New ListItem("select")) _
                    Or Me.Items.Contains(New ListItem("Select"))) Then
                    Me.Items.Insert(0, New ListItem("Select"))
                End If
            End If
        End Sub

The JavaScript function AutoComplete accepts as argument the custom DropDown that fired the event. Once the dropdownlist is selected, keypressBuffer of dropdown list stores the letters as they are typed.The JavaScript next determines the key that is pressed and appends the same to keypressBuffer. The control then loops through all the items of the dropdownlist and checks each item for a match against the stored buffer. If a match is found, that item is selected.

 function AutoComplete(obj)
{
    var undefined;
    if (obj.keypressBuffer == undefined)
    {
        obj.keypressBuffer = '';
    }

    var key = String.fromCharCode(window.event.keyCode);
    obj.keypressBuffer += key;
    obj.keypressBuffer = obj.keypressBuffer.toLowerCase();
    var iLength = obj.options.length;
    var bool=false;

    for (var i=0; i < iLength; i++)
    {
        var strText = obj.options[i].text;
        strText = strText.toLowerCase();
        if (strText.indexOf(obj.keypressBuffer,0) == 0)
        {
            obj.selectedIndex = i;
            bool=true;
            return false;
        }
    }
    if (bool==false)
    {
    return false;
    }
} 

In order to initialize the keypressBuffer, deselect the custom DropDownList by selecting/clicking elsewhere on the page. This will fire the onblur event. The function Reset that accepts custom DropDown that fired the event as argument will initialize the buffer.

 function Reset(obj)
 {
  obj.keypressBuffer='';
 } 

History

  • 25th June, 2008: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here