TUTORIAL #8: Creating An AutoComplete TextBox With AJAX

There’s this incredible resource in the AJAX Control Toolkit, and it’s about time we started using it. Today I am going to talk about the AutoComplete Extender, and how simple it is to rig up to an existing ASMX web service. As usual, I will provide the code at the end of this post in both C# and VB.NET. Let’s start at the beginning:

1) Create a new web site.

2) Create a new ASMX web service.

Right-click on the project, and choose “Add New Item…” From the dialog box, choose Web Service, and name the service NCAA.asmx (I’ll explain the name later.) Also, for our demo, we’re going to leave the code in one single file. Uncheck the “Place code in a seperate file” box.

3) Write a quick web method.

We’ll be making this more complicated later, but for now, we’re going to write a simple web service that is meant for the AutoComplete Extender. For this control, our method must have this signature:

public string[] GetTeamList(string text)

So for now, here’s the full code to put inside your ASMX file:

using System;
using System.Collections;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;


namespace AutoComplete
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class ncaa : System.Web.Services.WebService
{
[WebMethod]
public string[] getTeamList(string prefixText)
{
string[] teamName = new String[6];
teamName[0] = "Bowling Green State University";
teamName[1] = "Ohio State University";
teamName[2] = "Ohio University";
teamName[3] = "Cleveland State University";
teamName[4] = "University of Cincinnati";
teamName[5] = "University of Dayton";
return teamName;
}
}
}

4) We should verify our web service works.

Right click on your ASMX file, and choose “View in Browser.” Clicking on the method name, GetTeamList, will ask you for a “prefixText” value. That value isn’t used yet, so just click the Invoke button to see our list of colleges returned in XML.

5) Now we need add a textbox.

We’re actually going to add a few things to our Default.aspx page, but the first thing to do is add a standard TextBox control to the page. You should be able to grab that from your toolbox. The other things to add require a potential download first. I’ll show you the completed HTML after step #9.

6) Get the ASP.NET AJAX Library.

You only need to do this if you’re not using the ASP.NET 3.5 framework. Here is the link to the AJAX library downloads.

7) Get the AJAX Control Toolkit.

The control toolkit is an open source project on CodePlex, and you can download it here. Unless you’re really interested in contributing/taking it apart, all you really need is the link to the DLL Only. Save that to your computer, and then you need to add it to your Toolbox.

8) Add it to your VS Toolbox.

Here’s the quick way to get those new controls and extenders into your Visual Studio toolbox:

  1. Pin out your toolbox by clicking on the pushpin icon at the top.
  2. Right-click on the toolbox and choose “Add Tab”
  3. Give it a name like “AJAX Control Toolkit.”
  4. Drag the toolkit .DLL file from your computer to the new tab you created.
  5. You should now see your new controls in your toolbox.

9) Add our AJAX elements to the page.

Now we need to add an AJAX ScriptManager and a new AutoCompleteExtender to our page. You can either type them, or just drag them from your toolbox. Here’s what your Default.aspx file should look now:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AutoComplete._Default" %>
<%
@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<
html xmlns="http://www.w3.org/1999/xhtml" >
<
head runat="server">
<
title>Jeff Blankenburg | AutoCompleteExtender</title>
<
link href="style.css" rel="stylesheet" type="text/css" />
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<
asp:TextBox ID="collegeteam" runat="server"></asp:TextBox>
<
cc1:AutoCompleteExtender ID="collegeteamextender" runat="server" ServicePath="ncaa.asmx" ServiceMethod="getTeamList" MinimumPrefixLength="3" CompletionSetCount="10" TargetControlID="collegeteam">
</
cc1:AutoCompleteExtender>
</
div>
</
form>
</
body>
</
html>

10) Some explanation for the HTML…

You’ll notice that I added some properties to the controls that are on our page, so let me explain what they are.

  • Service Path – this is the web service that we are going to call
  • Service Method – this is the method in that web service that we are calling.
  • Minimum Prefix Length – this is the number of characters a user must enter before the extender will start calling the web service. If you’ve got thousands or millions of possible return values, I’d make this 3 or 4, at a minimum.
  • Completion Set Count – this forces the control to only show a specific number of results (you need to modify your web service for this to work).

11) Run the web site.

At this point, we should have a fully functional AutoComplete extender. You can run the site to check it out. Just start typing in the textbox to see what happens. But we’re pulling back a static list of data. That’s not very interesting at all. I want to do something realistic with this functionality.

12) Web Service += Usefulness

The reason that I called my web service NCAA is because I want to allow my users to choose from a list of colleges as they are typing. The first thing we’ll need then, is a database of colleges. Here’s my database of all of the Division I schools, with their names, mascots, and hex colors. Now we need to modify our web service so that we’re pulling results out of the database based on our text typed in the TextBox. Here’s my new web service code (you can just copy and paste over the old stuff.)

using System;
using System.Collections;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;


namespace AutoComplete
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class ncaa : System.Web.Services.WebService
{
[WebMethod]
public string[] getTeamList(string prefixText)
{
DataSet teams = new DataSet();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string sql = "SELECT team_name FROM team WHERE team_name LIKE '" + prefixText + "%'";
SqlCommand sqlCmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataAdapter sqlAdpt = new SqlDataAdapter();
sqlAdpt.SelectCommand = sqlCmd;
sqlAdpt.Fill(teams);
string[] teamName = new String[teams.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (DataRow row in teams.Tables[0].Rows)
{
teamName.SetValue(row["team_name"].ToString(), i);
i++;
}
}
catch { }
finally
{
conn.Close();
}
return teamName;
}
}
}

You’ll notice that without modifying our .aspx file, we can completely update the functionality behind our web service. This seperation can be invaluable when building applications from web services, because you don’t want a change in one thing to potentially break another.

13) What about that CompletionSetCount?

So I mentioned earlier that you can set the number of results you want returned so that you don’t end up with a huge, unmanageable list. This will require a small change to your web service, but nothing significant. Without these changes, your CompletionSetCount value will just be ignored. The first change is that we need to receive a second parameter (an integer) in our WebMethod. That’s right, the extender just sends it as a second parameter to your method. The second change, then, is just to modify your method to utilize that value. Here’s my final web service source code, using this added feature:

using System;
using System.Collections;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;


namespace AutoComplete
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class ncaa : System.Web.Services.WebService
{
[WebMethod]
public string[] getTeamList(string prefixText, int count)
{
DataSet teams = new DataSet();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string sql = "SELECT TOP " + count + " team_name FROM team WHERE team_name LIKE '" + prefixText + "%'";
SqlCommand sqlCmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataAdapter sqlAdpt = new SqlDataAdapter();
sqlAdpt.SelectCommand = sqlCmd;
sqlAdpt.Fill(teams);
string[] teamName = new String[teams.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (DataRow row in teams.Tables[0].Rows)
{
teamName.SetValue(row["team_name"].ToString(), i);
i++;
}
}
catch { }
finally
{
conn.Close();
}
return teamName;
}
}
}

Demo

Here’s a link to the active demo. Because my hosting provider does not support SQL Express (we can talk about CrystalTech later), I am actually running it from a full SQL 2005 database, but the MDB I provided is merely a copy of the table I am using.

Click to see the AutoComplete demo.

Source Code

Click to download the AutoComplete demo in C#. Click to download the AutoComplete demo in VB.NET.

kick it on DotNetKicks.com

2 thoughts on “TUTORIAL #8: Creating An AutoComplete TextBox With AJAX

  1. I am developing in VS2005 on 2.0 framework. Can I get this to work in that environment? Your tutorial is the most complete/succinct I have found on making an autocomplete that checks against a DB and I am quite eager to do this.

  2. I have problem with: “[System.Web.Script.Services.ScriptService]””using System.Linq;””using System.Xml.Linq;”It´s not recognized.How I can solved this problem?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s