AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=775&pId=-1
Building a Type-Ahead Dropdown Control
page
by Michael Libby
Feedback
Average Rating: 
Views (Total / Last 10 Days): 30062/ 65

Introduction

Microsoft's DropDownList control for ASP.NET does not offer type-ahead functionality.  Often users have to scroll through hundreds of items before making a selection.  This article shows how to easily implement dropdown type-ahead functionality that uses keystrokes to find an exact selection, making scrolling optional.  The article first shows how to do this in a simple ASP.NET web page, and then with the use of a web server control that can be shared across multiple projects.

Figure 1- Web Page with Type-Ahead Dropdown Controls

A Simple ASP.NET Type-Ahead Dropdown

The following steps show how to implement a type-ahead dropdown on an ASP.NET page:

1.    Create a new Visual Studio 2005 C# web site called TADropDownTest.

2.    Drag a DropDownList control from the Toolbox onto the default.aspx web page, assign its id to ddlTest, and enter some common character test items by clicking on the elipsis ("…") in the items property (for example: ad, adam, adapt, adhoc, adope, adopt…).

3.    Add the following C# code to Default.aspx.cs:

Listing 1 - Default.aspx.cs Code

const string js = "TADDScript.js";
protected void Page_Load(object sender, EventArgs e)
{
  Type typ = GetType();
  if (!Page.ClientScript.IsClientScriptIncludeRegistered(typ, js))
  Page.ClientScript.RegisterClientScriptInclude(typ, js, js);
  ddlTest.Attributes.Add("onKeyDown""TADD_OnKeyDown(this);");
}

4.    Add a JavaScript file called TADDScript.js to the project with the following syntax:

Listing 2 - JavaScript file TADDScript.js

var typeAheadData = 
{
  keyStrokes:"",
  focusDDLId:"",
  ResetOnNewDDLRequest:function(id) 
  {
    if (this.focusDDLId != id) 
    {
      this.focusDDLId=id; this.keyStrokes="";
    }
  }
};
function TADD_OnKeyDown(tb)
{
  if (event.ctrlKey)
  return; 
  
  typeAheadData.ResetOnNewDDLRequest(tb.id);
      
  switch (event.keyCode)
  {
    case 38: 
    case 40:  
      typeAheadData.keyStrokes = "";
      return; 
    case 13:  
      typeAheadData.keyStrokes = "";
      tb.fireEvent("onchange");
      return; 
    case 8:    
      if (typeAheadData.keyStrokes.length > 0)
      {
        typeAheadData.keyStrokes = typeAheadData.keyStrokes.substr(0,   
        typeAheadData.keyStrokes.length-1);
      }
      event.cancelBubble = true;
      event.returnValue = false;
      break;
      default:
      var c = '';
      if ((event.keyCode>=96)&&(event.keyCode<=105)) //Numbers 0-9
      {
         c=(event.keyCode-96).toString();
      }
      else
      {
         c=String.fromCharCode(event.keyCode).toLowerCase();
      }
      if (c != null)
      {
        typeAheadData.keyStrokes += c;
      }
      event.cancelBubble = true;
      event.returnValue = false;
      break;
  }
  if (TADD_SelectItem(typeAheadData) == false)
  {
    typeAheadData.keyStrokes = "";
    window.status="Not found"; 
  }
  else
  {
    tb.fireEvent("onchange");
    window.status="KeyStrokes: " + typeAheadData.keyStrokes;
  }
}
function TADD_SelectItem(typeAheadData)
{
  var ddl = document.getElementById(typeAheadData.focusDDLId);
  ddl.selectedIndex = -1;
  if (typeAheadData.keyStrokes.length > 0)
  {
    for (i = 0; i < ddl.options.length; i++) 
    {
      if ((ddl.options[i].text.length >= typeAheadData.keyStrokes.length)
      &&  (ddl.options[i].text.substr(0,
      typeAheadData.keyStrokes.length).toLowerCase() == typeAheadData.keyStrokes))
      {
        ddl.selectedIndex = i;
        return true;
      }
    }
  }
  return false;
}

5.    Run the web application.  Click on the dropdown when the default.aspx page displays.  Now type some text.  If you entered test data from step 2 you will note that typing "ada" will select "adam" and then another character "p" will select "adapt".

Note: Characters entered display in the browser's status bar.

The Type-Ahead DropDownList uses multiple characters to narrow a search to the exact entry no matter how large the list.  The enclosed code has been used with more than 5,000 entries with thousands of users without problems.

Building a Type-Ahead DropDown Web Control Library

Type-Ahead Dropdown can also be implemented in a web control library and used system-wide in place of ASP.NET's DropDownList control.  The following steps show how this is done:

1.    Right-click on the solution, select Add, New Project, Project types: Windows, Templates: Web Control Library.  Enter MyWebControls for the name and click OK.

2.    Add JavaScript file, TADDScript.js (shown above in Listing 2) to the project.  Right-click on this file in Solution Explorer, select Properties, and then set the file's Build action to Embedded Resource.

3.    Right-click on file WebCustomControl1.cs in Solution Explorer and rename the file to TADropDown.cs.  Now change the file's syntax to the following:

Listing 3- TADropDown Web Custom Control

using System;
using System.ComponentModel;
using System.Web.UI;
using System.IO;
using System.Reflection;
 
namespace MyWebControls
{
  [DefaultProperty("Text")]
  [ToolboxData("<{0}:TADropDown runat=server></{0}:TADropDown>")]
  public class TADropDown : System.Web.UI.WebControls.DropDownList
  {
    const string js = "TADDScript.js";
    protected override void OnPreRender(EventArgs e)
    {
      base.OnPreRender(e);
      Type typ = this.GetType();
      if (!Page.ClientScript.IsClientScriptIncludeRegistered(typ, js))
      {
        Page.ClientScript.RegisterClientScriptInclude(typ, js, js);
        if (!File.Exists(Page.Request.PhysicalApplicationPath + js))
        {
          // Note: If you changed the project name then change "MyWebControls"
          // to the name of your project. 
          Stream rs = Assembly.GetExecutingAssembly().GetManifestResourceStream(
             "MyWebControls." + js);    
          StreamReader sr = new StreamReader(rs);
          StreamWriter sw = 
             File.CreateText(Page.Request.PhysicalApplicationPath+js);
          sw.Write(sr.Read());
          rs.Close(); 
          sr.Close(); 
          sw.Close();
        }
      }
      Attributes.Add("onKeyDown""TADD_OnKeyDown(this);");
    }
  }
}

4.    Right-click on the TADropDownTest project and select Add Reference, Projects tab, Project name: MyWebControls and press OK.

5.    Open TADropDownTest file Default.aspx and drag TADropDown from the MyWebControls Components toolbar onto the web form. Assign its id to taddTest, and enter some common character test items by clicking on the elipsis ("…") in the items property (for example: ad, adam, adapt, adhoc, adope, adopt…).

6.    Make sure that your web application has runtime write permissions to its directory.  This will allow the Javascript file to be written to the server at runtime.

7.    Run the application and the new TADropDown web control will behave just like its web form's predecessor.

Add the MyWebControls.dll to the toolbar and you will be able to drag the TADropDown Control to any project's web form just as easily as ASP.NET's DropDownList control.

Downloads

[Download Sample]

Summary

In this step-by-step article, you have seen how to implement the type-ahead functionality in a dropdown list with the help of an example.


Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-05-18 8:47:26 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search