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.