Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

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

4.88/5 (9 votes)
16 Dec 2012CPOL2 min read 46.1K   778  
This tip describes how the auto complete textbox can be created using the AJAX Control extender. We will also implement a small application to show how this can be done.

Introduction 

This tip describes how the auto complete textbox can be created using the <code>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 <code>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.

C#
[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.

XML
<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)