Using AutoComplete in the AJAX Toolkit in C#


V4 Ajax Tutorials
Server Intellect Cloud Hosting

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
Jim O'Neill said:

Where you have this code:

return db.tblNames.Where(n=> n.name.StartsWith(prefixText)).OrderBy(n => n.name).Select(n => n.name).Take(count).ToArray();

...what is "n" and where does this get set? Also, where is the value of 'count' determined?

This code doesn't crash, but it doesn't do anything either. I'm missing a piece of something.

Posted Aug 11, 2010 2:23 PM
Orange County Homes for Sale said:

The post is written in very a good manner and it entails many useful information for me. I am happy to find your distinguished way of writing the post. Now you make it easy for me to understand and implement the concept. Thank you for the post.

Posted Nov 12, 2010 10:15 AM
Orange County Homes for Sale said:

The post is written in very a good manner and it entails many useful information for me. I am happy to find your distinguished way of writing the post. Now you make it easy for me to understand and implement the concept. Thank you for the post.

Posted Nov 15, 2010 12:55 AM
no employment verification payday loans no fax said:

I have to admit that I have been searching for this information for a long time. Reading this wonderful publication I have known many new things about the Ajax toolkit, which I have not known before. As I see all your articles are informative and full of valuable information so I will definitely bookmark your website and wait for more such great posts like this one. So huge thanks!

Posted Nov 29, 2010 5:35 PM
priligy 30mg × 90 pills said:

priligy 30mg × 90 pills

Posted Dec 5, 2010 9:56 AM
Freelance SEO India said:

India’s leading Freelance SEO India services provider with main competency in Search Engine Optimization of websites.

Posted Dec 29, 2010 11:20 AM
Veasna said:

Hi mate, This is not working with mysql database, is it? Could you please let me know if it's possible to do with mysql? Thanks

Posted Jan 16, 2011 10:31 PM
mahmud111 said:

nice and effective post .This will help everyone.

<a href="http://www.play-racing-games.net">racing games</a>

Posted Feb 5, 2011 7:51 AM
Jyothi said:

aaaaaaaaaaaaaaa

Posted Feb 14, 2011 2:11 AM
Jyothi said:

Nice

Posted Feb 14, 2011 2:11 AM
art said:

Good effective so much thanks for this ..

Posted Mar 8, 2011 4:18 AM
love quotes said:

Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.

Posted Mar 8, 2011 4:20 AM
Lou said:

Hy!

Thank you sooo much for your article!

At first it wasn't working maybe because the toolkit got updated since your post...

Anyway, i had to replace the <asp:ScriptManager /> by <asp:ToolkitScriptManager />

Thanks again

Posted Apr 12, 2011 5:07 AM
magazines said:

Very informative post thanks for share this with us i highly appreciate you for this information thanks once again for sharing information like this!

Posted May 26, 2011 3:54 AM
nikeshoeslocker said:

Thanks so much for providing individuals with such a spectacular possibility to read critical reviews from this web site. It is always very useful and also full of amusement for me personally and my office acquaintances to visit your web site no less than three times weekly to read the fresh guidance you have got. Of course, we are usually amazed for the surprising things served by you.www.nikeshoeslocker.com

Posted Jun 1, 2011 1:55 AM
Jidheesh said:

I tried with this code. But getting Compilation Error in line

NamesDataContext db = new NamesDataContext();

If anyone knows please help me

many thanks in advance!!!

Posted Jul 20, 2011 7:13 AM
www.gucci2you.com said:

www.gucci2you.com

Posted Aug 6, 2011 3:42 AM
Portable pa system said:

It is informative blog.I am wondered to see the way in which the information are distributed here.

Posted Aug 10, 2011 4:35 AM
Eric Morgan said:

Excellent. This was concise and told me exactly what steps to take.

Posted Aug 29, 2011 3:07 PM
Nike Zapatillas said:

Buscando en Internet para los guantes de béisbol que puede producir resultados varias veces de ir de tienda en tienda.

Posted Nov 18, 2011 9:29 PM
Gaurav Yadav said:

This is best one article so far I have read online. I would like to appreciate you for making it very simple and easy. I have found another nice post related to this post over the internet which also explained very well. For more details you may check it by visiting this url.......

mindstick.com/.../a7e242ef-fd21-4

Thanks

Posted Jan 3, 2012 3:32 AM

Leave a Comment