Using AutoComplete in the AJAX Toolkit in C#


Server Intellect


Using AutoComplete in the AJAX Toolkit in C#

This tutorial was created with and aimed toward users of Visual Studio.NET 2008. 2005 can be used, but Microsoft's ASP.NET AJAX Extensions, which can be downloaded at this location, must be installed.
Also, if using 2005, some additional steps may be required that are not listed in this article.

Microsoft have a Control Toolkit that is not included with the .NET Framework, but can be downloaded from www.codeplex.com/AjaxControlToolkit. This Toolkit is constantly being updated and consists mainly of AJAX Extenders for existing ASP.NET Controls.
By now, you are bound to have seen Google's implementation of the AutoComplete AJAX control for commonly searched terms. The Google search box will now offer you commonly searched for phrases as you type! This means that the form will guess what you are typing, and provide matches for you to choose.

Try Server Intellect for Windows Server Hosting. Quality and Quantity!

In this tutorial, you will learn how to implement something similar using the AutoComplete AJAX Control and a Web Method.
We will be using a SQL database to match the typed text against and retrieve matches to the user.

We start by creating the database. Open up a new C# web application project in Visual Studio, then right-click the App_Data folder in Solution Explorer and choose Add New Item.. SQL Server Database. We will create one table with two columns - id, name. We will create a database of names. For this example, it will not be a comprehensive list of names, but we will add some sample data once we have designed the table.
We set the id to data type int, and name to data type varchar(50). We also set the id column as Primary Key and Identity Specification, then save the table and close.

Next, right-click the project in Solution Explorer and choose Add ASP.NET Folder > App_Code. Then right-click the App_Code folder and Add New Item.. LINQ to SQL Classes. We will create a class to represent our database table so that we can use LINQ to retrieve records from our database as we type.
We should be presented with the Object Relation Designer. Here, we can goto Server Explorer and drag our table to the design view, then save. This will allow VS to create the class representation for us. We will then use LINQ to interact with this class and then save the changes back to the database.

Next, we will build our Web Method in the back-end of our ASPX page. Let's start by making sure we are referencing the LINQ namespace:

using System.Linq;

If you're ever in the market for some great Windows web hosting, try Server Intellect. We have been very pleased with their services and most importantly, technical support.

We can then create our Web Method like so:

[System.Web.Services.WebMethod]
public static string[] GetNames(string prefixText, int count)
{
NamesDataContext db = new NamesDataContext();
return db.tblNames.Where(n=> n.name.StartsWith(prefixText)).OrderBy(n => n.name).Select(n => n.name).Take(count).ToArray();
}

We chose Server Intellect for its dedicated servers, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar.

Here we are creating a Web Method within the page. We could create this as a Web Service, but for this example we are only using it on this page.
We first instantiate our LINQ to SQL Class we created earlier, then we use Lambda Expressions to select data from the database that match what the user is typing in. This method will be called from the AJAX AutoComplete Extender when the user types into the textbox. The AJAX Extender will maange the calling of the method, and also the retrieval of the string array.

We will also have a button that will move the chosen suggested text to a label:

protected void butName_Click(object sender, EventArgs e)
{
lblChosenName.Text = "You chose the name " + txtName.Text + ".";
}

We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.

Our entire code-behind will look something like this:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

[System.Web.Services.WebMethod]
public static string[] GetNames(string prefixText, int count)
{
NamesDataContext db = new NamesDataContext();
return db.tblNames.Where(n=> n.name.StartsWith(prefixText)).OrderBy(n => n.name).Select(n => n.name).Take(count).ToArray();
}

protected void butName_Click(object sender, EventArgs e)
{
lblChosenName.Text = "You chose the name " + txtName.Text + ".";
}
}

Now we have built our Web Method, we will implement it into our ASPX page. We will first add the following ASP.NET Controls: a TextBox, Button and Label. Also make sure there is a ScriptManager, and an UpdatePanel if you want the form to make use of Asynchronus Postbacks.

<form id="form1" runat="server">
<asp:ScriptManager ID="SM1" runat="server" />

<asp:UpdatePanel ID="UP1" runat="server">
<ContentTemplate>
Name:
<asp:TextBox ID="txtName" runat="server" />
<br />
<asp:Button ID="butName" runat="server" Text="Go" onclick="butName_Click" /><br />
<br />
<asp:Label ID="lblChosenName" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</form>

Try Server Intellect for Windows Server Hosting. Quality and Quantity!

Now if we go into Design view of our ASPX page, we can click on the SmartTag of the TextBox and choose Add Extender. This will only be available if we have the AJAX Toolkit installed.
Once you choose to Add Extender, you can choose the AutoComplete option. This will add a Custom Control to the page, named AutoCompleteExtender. We need to set the ServiceMethod attribute to the name of our Web Method, and also set the TargetControlID to that of the TextBox we will be using. Setting AutoComplete=Off on the textbox will turn off the built-in autocomplete in IE and FireFox.

<form id="form1" runat="server">
<asp:ScriptManager ID="SM1" runat="server" />

<asp:UpdatePanel ID="UP1" runat="server">
<ContentTemplate>
Name:
<asp:TextBox ID="txtName" runat="server" AutoComplete="Off" />

<cc1:AutoCompleteExtender ID="txtName_AutoCompleteExtender" runat="server"
TargetControlID="txtName" MinimumPrefixLength="1" ServiceMethod="GetNames">
</cc1:AutoCompleteExtender>
<br />
<asp:Button ID="butName" runat="server" Text="Go" onclick="butName_Click" /><br />
<br />
<asp:Label ID="lblChosenName" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</form>

The AutoComplete Extender is also smart enough to provide caching - it will detect if the search term has been previously entered, and if so, it will not need to make another call to the database; it will retrieve results from cache.

Download Project Source - Enter your Email to be emailed a link to download the Full Source Project used in this Tutorial!



100% SPAM FREE! We will never sell or rent your email address!
 


Comments
Ab0 said:

Very nice tutorial, thank you

Posted Oct 7, 2008 6:44 AM
vasja said:

Very helpful ty!

Posted Oct 16, 2008 5:49 AM
b_e_n_j_a_m_i_n said:

I love these samples.

Can i make a small suggestion - that a compiled version be left onsite. Can be a pain to download something and run just to find its not what you're after.

Thanks for the tips though.

Cheers.

Posted Nov 4, 2008 12:01 PM
Jamshid said:

Thanks a lot!

Posted Nov 5, 2008 12:38 AM
Raj said:

Hi,

I am wondering, how we will pass the parameter values in method GetNames

Hoping to see how...........

Posted Nov 5, 2008 12:48 AM
Feisal Gele said:

Realy it is nice tutorial, it is posible some one to change vb.net?.

Thanks

Posted Nov 5, 2008 5:14 AM
潘杰 said:

也许是我的英语不好看的不是很懂吧!我要继续错come on!

Posted Nov 5, 2008 10:34 PM
Anas said:

Very weak tutorial ,

Posted Nov 6, 2008 3:15 AM
Ivan said:

Interesting tutorial!!

Congratuations!!!

Posted Nov 7, 2008 5:59 AM
Jagwinder said:

Can we return text and id using this control

Posted Nov 8, 2008 6:34 AM
David said:

The sample code does even include the csproj file. Also, I don't have an Add -> ASP.NET Folder -> App_Code option on the menus.

Posted Nov 10, 2008 11:09 PM
Babak said:

Thank you for this very helpful tutorial. Please continue the excellent work.

Posted Nov 14, 2008 11:00 AM
Dilli said:

Simple but very nice tutorial

Posted Nov 14, 2008 12:45 PM
Abraham said:

Very good tutorial

Thanks

Posted Dec 9, 2008 3:02 AM
Adam said:

i have an issue with the autocomplete, using C#. i need more then 1 autocomplete on a page, and each previous value is to be used as 'criteria'

for example first autocomplete you type first name, select the name you want and on click it gets saved to a txtbox on the side.

the second autocomplete has to use the saved value as criteria as you search for last names that have same first name. (does it make sense?)

my problem is that the *.cs files in my App_Folder cannot see the values from my Default.aspx and im stuck (still fresh with this stuff)

tried session variables and cookies to no avail but may of done it wrong. any one able to help?

oh and not using DB im using API call to other software to get my values

Posted Jan 15, 2009 9:58 PM
Shahaji said:

Very helpful

Posted Mar 24, 2009 4:32 AM
Laxmi Prakash said:

I am using the same code on content page but it not call the Web service method. Is it work with master page or i need to do some modification in the code?

Posted Oct 7, 2009 1:40 PM
David said:

Nice tutorial. Would love to see the same exact thing done on a page using Master Pages.

Posted Jan 6, 2010 8:03 AM
Nemanja Todić said:

Great one! Thx a lot.

Posted Feb 14, 2010 10:03 AM

Leave a Comment