Click here to Skip to main content
15,117,318 members
Articles / Web Development / ASP.NET
Posted 23 Sep 2011


31 bookmarked

Using AJAX AutoCompleteExtender for autosuggest

Rate me:
Please Sign up or sign in to vote.
4.84/5 (13 votes)
11 Sep 2012CPOL2 min read
Using Ajax AutoCompleteExtender for a simple autosuggest feature.



In the present scenario, we need our text boxes to act more user friendly, so auto suggest is a feature that makes it more user friendly. Moreover the chance of making typo mistakes also reduces. This article will help you in adding a simple auto suggest feature using AJAX AutoCompleteExtender.


A service is used to call the data from database. This autosuggest will populate top ten records on the basis of the letter entered by you. For example, if we type “A”, the top ten names beginning with the letter “A”, then we make it “An”, then top 10 beginning with “An”.

Using the Code

Code is populating auto suggest for a company. What we need from the service is the name of the company and its ID. So here is the method that we are writing in the service to get the top 10 companies starting with the text typed by the user in the TextBox.

The name of the service is “CompanyServiceForAutoSuggest” in which exists method GetCompanyList which includes two parameters:

  • prefixText” the text to be searched to populate the autosuggest
  • count” the maximum number of records in the auto suggest

The method returns an array string, which includes company name and its ID.

public String[] GetCompanyList(String prefixText, Int32 count)
    String[] strList = null;
    List<companymasterbo> objCompanyList = new List<companymasterbo>();
    List<string> strCompanyList = new List<string>();
    short i;
    UtilityServiceClient lObjUtilityServiceClient = null;
    CompanyMasterBO lObjCompanyMasterBO = null;
    lObjCompanyMasterBO = new ARGI.Vulcan.ServiceLayer.UtilityService.CompanyMasterBO();
    lObjCompanyMasterBO.Company = prefixText.Replace("'","''").ToString().Trim();
    lObjCompanyMasterBO.Count = count;          
        lObjUtilityServiceClient = new UtilityServiceClient();                
        objCompanyList = lObjUtilityServiceClient.GetCompanyList
        (lObjCompanyMasterBO);// Method to get top 10 company from database
/* This is my query to get the records 
 @sql varchar(4000)                                        
 set @sql = 'SELECT top ' + convert(varchar(10),@p_Count)  + 
 		' comCompanyMasterID,comCompanyName  
 from dbo.[CompanyMaster]  where comCompanyName LIKE 
exec (@sql) */
        if (objCompanyList.Count > 0)
            for (i = 0; i < objCompanyList.Count; i++)
                  CreateAutoCompleteItem(objCompanyList[i].Company, Convert.ToString(
            strList = new String[10];
            strList = strCompanyList.ToArray();
            //strList = new String[1];
            //strList[0] = "No Match Found";
    catch (System.ServiceModel.FaultException FaultExp)
    catch (Exception ex)
        if (lObjUtilityServiceClient != null)
            lObjUtilityServiceClient = null;
        if (lObjCompanyMasterBO != null)
            lObjCompanyMasterBO = null;
    return strList;

I have created a control, as it needs to be placed at many locations. The name of my control is ucCompany.

On the ucCompany.ascx page, write the following lines:

 <asp:TextBox ID="txtAutoCompleteforCompany" 
	name="txtAutoCompleteforCompany" runat="server"
         onblur="showMessage()" autocomplete="off"></asp:TextBox>
	ID="txtAutoCompleteforCompany_waterMark" runat="server"
	WatermarkText="Add New Company..."Enabled="true">
<div id="listPlacement" class="cls_listPlacement"></div>
<ajaxtoolkit:AutoCompleteExtender ID="txtAutoCompleteforCompany_AutoCompleteExtender"
	MinimumPrefixLength="1" TargetControlID="txtAutoCompleteforCompany" 
	runat="server" OnClientItemSelected="setCompanyMasterID" 
<input type="hidden" id="hdnCompanyMasterId" 
	name="hdnCompanyMasterId" runat="server" value="0" />
<input type="hidden" id="hdnCompanyName" 
	name="hdnCompanyName" runat="server" value="" />

ServicePath is the actual path where my service is saved. So my service will be called here. TargetControlID is the name of the control on which auto suggest will display its result. OnClientItemSelected we are calling a JS function named "SetCompanyMasterID", by using this method, I am setting the ID and Name in a hidden variable, to use them as and when required.

Add the script tag in ucCompany.ascx and define the js function:

<script type="text/javascript">
function setCompanyMasterID(source, eventargs)
  document.getElementById ("hdnCompanyMasterId.ClientID").value = 
  document.getElementById ("hdnCompanyName.ClientID").value = 
     document.getElementById ("txtAutoCompleteforCompany.ClientID").value;

On the ucCompany.ascx.cs file, we are creating two methods:

  • "GetCompanyMasterId" to fetch the Company ID 
  • "GetCompanyName" to get the name of the company
public int GetCompanyMasterId()
        if (hdnCompanyMasterId.Value.Trim() != String.Empty && 
        		hdnCompanyMasterId.Value.Trim() != "0")
            if (hdnCompanyName.Value.Trim() == 
                return Convert.ToInt32(hdnCompanyMasterId.Value);
                return 0;
            return 0;

public string GetCompanyName()
        if (txtAutoCompleteforCompany.Text.Trim() != String.Empty)
            return txtAutoCompleteforCompany.Text.Trim();
            return string.Empty;


My control was placed inside another control. So I lost the value of ID and Name after the post back. So I wrote my JS method on server side and if the page load occurs, I call my JS method forcefully. In case you are using this control directly, then this step won’t be required.

protected void Page_Load(object sender, EventArgs e)
public void RegisterClientScript()
 StringBuilder cstext2 = new StringBuilder();
 cstext2.Append("<script type=\"text/javascript\">
    	function setCompanyMasterID(source, eventargs) {");
 cstext2.Append("document.getElementById ('" + ClientID + 
     "_hdnCompanyMasterId').value = eventargs.get_value();");
 cstext2.Append("document.getElementById ('" + ClientID + 
     "_hdnCompanyName').value = document.getElementById 
     ('" + ClientID + "_txtAutoCompleteforCompany').value; }");
 cstext2.Append(" </script>");           
     ScriptManager.RegisterClientScriptBlock(this, GetType(), 
     "OnClientItemSelected", cstext2.ToString(),false);

Finally calling the control on a page, on the .cs file of the page, you can use:

// UcCompany is the ID of the control
string Company = UcCompany.GetCompanyName();	// To get the compnay name selected
   int CompanyMasterID = UcCompany.GetCompanyMasterId();// To get the ID of 
					// the company selected using auto suggest

Points of Interest

So far, I have used various Auto suggest using JavaScript and jQuery, this was the first time I was asked by my client that he needs Ajax control only. So I have implemented and found it interesting too. Hope it helps you too to add Auto suggest feature using AJAX.


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


About the Author

Anuja Pawar Indore
Program Manager Infobeans
India India
I have keen interest in learning new things, exploring more on a topic and being more versatile

Comments and Discussions

GeneralMy vote of 5 Pin
fredatcodeproject26-Feb-15 5:49
professionalfredatcodeproject26-Feb-15 5:49 
GeneralRe: My vote of 5 Pin
Anuja Pawar Indore26-Feb-15 20:36
MemberAnuja Pawar Indore26-Feb-15 20:36 
QuestionOutdated / Incomplete Pin
Member 93233398-Jul-14 14:57
MemberMember 93233398-Jul-14 14:57 
AnswerRe: Outdated / Incomplete Pin
Anuja Pawar Indore8-Jul-14 21:12
MemberAnuja Pawar Indore8-Jul-14 21:12 
AnswerRe: Outdated / Incomplete Pin
Anuja Pawar Indore26-Feb-15 20:36
MemberAnuja Pawar Indore26-Feb-15 20:36 
QuestionPost the entire solution? Pin
charles92227-Jul-13 16:16
Membercharles92227-Jul-13 16:16 
Is there any way you could post the entire Visual Studio solution, that is, the .sln file, the Web.config, and all the other files? I'm not able to get the downloaded code to build when I add it to a new VS 2010 ASP.NET solution. One thing that is needed for example, is the addition of
using System.Text;
for StringBuilder in ucCompany.ascx.cs. I'm getting compilation errors that suggest there is a problem with the Web.config file, or I am missing some source files.

I'm using Windows 7 and version of the AjaxControlToolkit.dll

Thank you
Questionthank you very much Pin
Member 269430711-Apr-13 4:51
MemberMember 269430711-Apr-13 4:51 
AnswerRe: thank you very much Pin
Anuja Pawar Indore11-Apr-13 4:55
MemberAnuja Pawar Indore11-Apr-13 4:55 
QuestionUnclear Pin
therealjordan4-Apr-13 9:25
Membertherealjordan4-Apr-13 9:25 
AnswerRe: Unclear Pin
Anuja Pawar Indore4-Apr-13 10:19
MemberAnuja Pawar Indore4-Apr-13 10:19 
QuestionError while retrieving data from service Pin
Brijesh Bhat3-Dec-12 21:31
MemberBrijesh Bhat3-Dec-12 21:31 
AnswerRe: Error while retrieving data from service Pin
Anuja Pawar Indore4-Dec-12 2:22
MemberAnuja Pawar Indore4-Dec-12 2:22 
GeneralRe: Error while retrieving data from service Pin
Brijesh Bhat5-Dec-12 1:25
MemberBrijesh Bhat5-Dec-12 1:25 
GeneralRe: Error while retrieving data from service Pin
Anuja Pawar Indore5-Dec-12 3:54
MemberAnuja Pawar Indore5-Dec-12 3:54 
GeneralRe: Error while retrieving data from service Pin
Brijesh Bhat5-Dec-12 22:50
MemberBrijesh Bhat5-Dec-12 22:50 
GeneralRe: Error while retrieving data from service Pin
Anuja Pawar Indore5-Dec-12 22:56
MemberAnuja Pawar Indore5-Dec-12 22:56 
QuestionGood Post Pin
Schin kulkarni.10-Oct-12 0:58
MemberSchin kulkarni.10-Oct-12 0:58 
AnswerRe: Good Post Pin
Anuja Pawar Indore10-Oct-12 3:49
MemberAnuja Pawar Indore10-Oct-12 3:49 
QuestionActually it's not working? Pin
Leo Rajendra Dhakal1-Aug-12 22:57
MemberLeo Rajendra Dhakal1-Aug-12 22:57 
AnswerRe: Actually it's not working? Pin
Anuja Pawar Indore3-Aug-12 0:59
MemberAnuja Pawar Indore3-Aug-12 0:59 
GeneralRe: Actually it's not working? Pin
Leo Rajendra Dhakal3-Aug-12 1:48
MemberLeo Rajendra Dhakal3-Aug-12 1:48 
GeneralRe: Actually it's not working? Pin
Anuja Pawar Indore3-Aug-12 3:38
MemberAnuja Pawar Indore3-Aug-12 3:38 
GeneralRe: Actually it's not working? Pin
Leo Rajendra Dhakal3-Aug-12 15:00
MemberLeo Rajendra Dhakal3-Aug-12 15:00 
Questionissue on trying the code Pin
Palavesam Pattan31-Oct-11 20:41
professionalPalavesam Pattan31-Oct-11 20:41 
AnswerRe: issue on trying the code Pin
Anuja Pawar Indore31-Oct-11 21:00
MemberAnuja Pawar Indore31-Oct-11 21:00 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.