Click here to Skip to main content
15,885,546 members
Articles / Programming Languages / Visual Basic
Article

DropDownWithAutoComplete

Rate me:
Please Sign up or sign in to vote.
3.41/5 (11 votes)
25 Jun 2008CPOL2 min read 31.2K   319   18   8
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.

VB.NET
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.

VB.NET
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.

VB.NET
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.

VB.NET
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.

VB.NET
 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.

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

History

  • 25th June, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Tata Consultancy Services
India India
I have been into Web development for past 2+ years.I've worked on areas like ASP.NET,VB.Net,Web services and web application framework DotNetNuke.I'm Microsoft Certified Professional in ASP.Net.

Comments and Discussions

 
Generaldoesn't work with ie 7 - ok with firefox Pin
Member 322743330-Jun-08 20:03
Member 322743330-Jun-08 20:03 
GeneralNice Job Pin
Saifi Hasan26-Jun-08 4:33
Saifi Hasan26-Jun-08 4:33 
GeneralSimple but very useful Pin
sudhu In LKO26-Jun-08 0:05
sudhu In LKO26-Jun-08 0:05 
GeneralHI Sir Pin
chanduice25-Jun-08 21:02
chanduice25-Jun-08 21:02 
GeneralRe: HI Sir Pin
Vivek Bhatnagar25-Jun-08 22:32
Vivek Bhatnagar25-Jun-08 22:32 
Generalgood job Pin
MCSDvikasmisra25-Jun-08 20:30
MCSDvikasmisra25-Jun-08 20:30 
GeneralRe: good job Pin
Vivek Bhatnagar25-Jun-08 20:54
Vivek Bhatnagar25-Jun-08 20:54 
GeneralVery useful Pin
Viram25-Jun-08 19:12
Viram25-Jun-08 19:12 
Indeed this article is very useful. This is most common functionality which we use in web projects. keep it up

Viram Pandey

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.