Click here to Skip to main content
Click here to Skip to main content

A Beginners Guide - Implementing Auto Suggest Functionality using Ajax Control Toolkit

By , 16 Dec 2012
 

Introduction 

This tip describes how the auto complete textbox can be created using the AJAXControlExtender. We will also implement a small application to show how this can be done.

Background  

The Ajax control toolkit provides the AutoCompleteExtender which can be used to create the autocomplete textbox without too much of overhead. We can also create the same thing using XMLHttpRequest or jQuery AJAX but perhaps I will write another tip for that.

The AutoCompleteExtender need to be attached with a textbox first. this can be done using the TargetControlID property of the extender. The Processing for getting the autocomplete results will be done at server side. typically this was done in a static method contained in a web service.

Using the code

The extender can then use this webservice to get the data from the server side and show the suggestions. 

So Let us create the a small application that will suggest the list of countries as user types into the textbox. Lets us start by looking at the Database. For now let us create a small database.

Now let us create a small webservice that will search the suggestion results from the database.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService 
{
    const string selectQuery = "SELECT Country FROM Countries WHERE Country LIKE @prefixText";

    [WebMethod]
    public string[] GetCountriesList(string prefixText)
    {
        string[] cntName = null;
        try
        {
            using (SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString))
            {
                sqlCon.Open();                
                using (SqlCommand sqlComd = sqlCon.CreateCommand())
                {
                    sqlComd.CommandType = CommandType.Text;
                    sqlComd.CommandText = selectQuery;
                    sqlComd.Parameters.Add(new SqlParameter("@prefixText", string.Format("{0}%", prefixText)));

                    using (SqlDataAdapter sqlAdpt = new SqlDataAdapter())
                    {
                        sqlAdpt.SelectCommand = sqlComd;

                        using (DataTable table = new DataTable())
                        {
                            sqlAdpt.Fill(table);
                            cntName = new string[table.Rows.Count];
                            int i = 0;
                            foreach (DataRow rdr in table.Rows)
                            {
                                cntName[i] = rdr["Country"].ToString().Trim();
                                ++i;
                            }
                        }
                    }
                }
            }
        }

        catch 
        {
            //something went wrong
        }

        return cntName;
    }
   
}

Now let us go ahead and hook the AutoCompleteExtender with this web service, configure it to use this GetCountriesList method, and make it work with the textbox on the page.

<asp:scriptmanager runat="server" id="ScriptManager1"><services>
	<asp:servicereference path="AutoComplete.asmx">
</asp:servicereference></services>
</asp:scriptmanager>
<div>
<asp:textbox runat="server" id="txtCountry" />
<ajaxtoolkit:autocompleteextender completioninterval="10" enablecaching="true" minimumprefixlength="1" servicemethod="GetCountriesList" servicepath="WebService.asmx" targetcontrolid="txtCountry" id="autoComplete1" runat="server">
</ajaxtoolkit:autocompleteextender></div>
</asp:scriptmanager>

Note: The ScriptManager is added to the page as it is required to make the AJAX control toolkit work. It will take care of registering all the scripts required for client server asynchronous communication to the client side. 

Now let us run the page and see the results.


 

The suggestion will be shown as the user will type in the textbox. these results are coming from serverside asynchronously. 

Point of interest

We have seen how to get implement the auto suggest functionality using the AJAX control toolkit's AutoCompleteExtender. The article was from the perspective of an Absolute beginner. There are other ways to do this too and i will perhaps post all those methods too. Also, There are a lot of useful controls in AJAX control toolkit, perhaps i will also talk about each of them one by one. 

History

  • 30 June 2012: First version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

AshishChaudha
Software Developer
India India
Member
I am a Software Engineer from Bhopal. I started my Career from Programming in ASP and now working as a Web Developer in ASP.Net (C#). I Love coding and always ready to gain new thing and always been towards Microsoft Technologies. Apart from coding my other hobbies are traveling, Internet Surfing, spending time with family and hang out with friends.
 
http://www.webtekspace.blogspot.in/

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questioncan't get ouput from your samplememberbuds6814 Feb '13 - 22:25 
I'd tried your code but not getting the output. My web will run but when enter letters in the textbox no autocomplete of characters will appear. Here's my code using ODBC connection because I'm using MS access DB.
 
WebService(Namespace:="http://tempuri.org/")> _
_
Public Class AutoComplete
Inherits System.Web.Services.WebService
Const selectQuery As String = "SELECT * FROM AccountManager WHERE Name LIKE @prefixText"
 
_
Public Function GetCountriesList(ByVal prefixText As String) As String()
Dim cntName As String() = Nothing
Try
Using sqlCon As Data.Odbc.OdbcConnection = New Data.Odbc.OdbcConnection("Dsn=circuitrts")
sqlCon.Open()
Using Comd As OdbcCommand = sqlCon.CreateCommand()
Comd.CommandType = CommandType.Text
Comd.CommandText = selectQuery
Comd.Parameters.Add(New OdbcParameter("@prefixText", String.Format("{0}%", prefixText)))
Using sqlAdpt As New OdbcDataAdapter()
sqlAdpt.SelectCommand = Comd
Using table As New Data.DataTable()
sqlAdpt.Fill(table)
cntName = New String(table.Rows.Count - 1) {}
Dim i As Integer = 0
For Each rdr As DataRow In table.Rows
cntName(i) = rdr("Name").ToString().Trim()
i += 1
Next
End Using
End Using
End Using
End Using
'something went wrong
Catch
End Try
Return cntName
End Function
GeneralMy vote of 4memberS.A.Esmaeily18 Dec '12 - 18:42 
Your coding is very well.But for a beginner (Like me),some parts of your code is a little complicate.
AnswerRe: My vote of 4memberAshishChaudha18 Dec '12 - 19:26 
Thanks Esmaeily, Where did you find complications, let me know I will try to make it easier.
 
Thanks
GeneralRe: My vote of 4memberS.A.Esmaeily21 Dec '12 - 18:40 
Thanks for your reply. You've used
<asp:servicereference path="AutoComplete.asmx">
What is "AutoComplete.asmx" file for? I need to know a little more about this file.
AnswerRe: My vote of 4memberAshishChaudha21 Dec '12 - 19:43 
Its webservice.aspx, I will update the code.
 
Thanks
Suggestiongo for jquery uimemberPrabu ram18 Dec '12 - 17:05 
Hi,
Appreciated your effort in writing this article. In my view AjaxContolToolkit is complex and it has lot of DLLs which we need to reference to.
 
However, jquery ui is small and easy to use and it is been widely used nowadays. Please check this page to know how simple and easy to get the auto complete text box. Check the options under Example (top right) to see various ways of getting data and different styles. Jquery UI is simply superb, give a try.
Prabu
 

Generalvotemembersagar wasule5 Jul '12 - 21:23 
Good one
GeneralRe: votememberAshishChaudha10 Jul '12 - 8:25 
Thanks buddy
GeneralMy vote of 5memberFarhan Ghumra1 Jul '12 - 19:16 
Excellent
GeneralRe: My vote of 5memberAshishChaudha10 Jul '12 - 8:26 
Thanks...

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 17 Dec 2012
Article Copyright 2012 by AshishChaudha
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid