Click here to Skip to main content
Licence CPOL
First Posted 25 Jun 2008
Views 14,976
Downloads 160
Bookmarked 18 times

DropDownWithAutoComplete

By | 25 Jun 2008 | Article
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Vivek Bhatnagar

Software Developer
Tata Consultancy Services
India India

Member

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.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Generaldoesn't work with ie 7 - ok with firefox PinmemberMember 322743320:03 30 Jun '08  
GeneralNice Job PinmemberSaifi Hasan4:33 26 Jun '08  
GeneralSimple but very useful Pinmembersudhu In LKO0:05 26 Jun '08  
GeneralHI Sir Pinmemberchanduice21:02 25 Jun '08  
GeneralRe: HI Sir PinmemberVivek Bhatnagar22:32 25 Jun '08  
Generalgood job PinmemberMCSDvikasmisra20:30 25 Jun '08  
GeneralRe: good job PinmemberVivek Bhatnagar20:54 25 Jun '08  
GeneralVery useful PinmemberViram19:12 25 Jun '08  
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    Rant Rant    Admin Admin   

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120604.1 | Last Updated 25 Jun 2008
Article Copyright 2008 by Vivek Bhatnagar
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid