Click here to Skip to main content
15,867,453 members
Articles / Web Development / ASP.NET

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 159.7K   4.2K   31   27
Using Ajax AutoCompleteExtender for a simple autosuggest feature.

UseAutoCompleteExtender/Company.JPG

Introduction

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.

Background

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.

C#
[WebMethod]
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;          
    try
    {
        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 
	'''+@p_CompanyFirstName+'%'''       
exec (@sql) */
        if (objCompanyList.Count > 0)
        {
            for (i = 0; i < objCompanyList.Count; i++)
            {
                strCompanyList.Add(AjaxControlToolkit.AutoCompleteExtender.
                  CreateAutoCompleteItem(objCompanyList[i].Company, Convert.ToString(
                  objCompanyList[i].CompanyMasterID.ToString())));
            }
            strList = new String[10];
            strList = strCompanyList.ToArray();
        }
        else
        {
            //strList = new String[1];
            //strList[0] = "No Match Found";
        }               
    }
    catch (System.ServiceModel.FaultException FaultExp)
    {
        throw;
    }
    catch (Exception ex)
    {
        throw;
    }
    finally
    {
        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:

XML
 <asp:TextBox ID="txtAutoCompleteforCompany" 
	name="txtAutoCompleteforCompany" runat="server"
         onblur="showMessage()" autocomplete="off"></asp:TextBox>
<ajaxtoolkit:TextBoxWatermarkExtender 
	ID="txtAutoCompleteforCompany_waterMark" runat="server"
	TargetControlID="txtAutoCompleteforCompany" 
	WatermarkText="Add New Company..."Enabled="true">
</ajaxtoolkit:TextBoxWatermarkExtender>
<div id="listPlacement" class="cls_listPlacement"></div>
<ajaxtoolkit:AutoCompleteExtender ID="txtAutoCompleteforCompany_AutoCompleteExtender"
	MinimumPrefixLength="1" TargetControlID="txtAutoCompleteforCompany" 
	CompletionSetCount="10"CompletionInterval="100" 
	ServiceMethod="GetCompanyList" 
	ServicePath="../UiHelper/CompanyServiceForAutoSuggest.asmx"
	runat="server" OnClientItemSelected="setCompanyMasterID" 
	CompletionListElementID="listPlacement">
</ajaxtoolkit:AutoCompleteExtender>
<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:

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

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
C#
public int GetCompanyMasterId()
{
    try
    {
        if (hdnCompanyMasterId.Value.Trim() != String.Empty && 
        		hdnCompanyMasterId.Value.Trim() != "0")
        {
            if (hdnCompanyName.Value.Trim() == 
		txtAutoCompleteforCompany.Text.Trim())
            {
                return Convert.ToInt32(hdnCompanyMasterId.Value);
            }
            else
            {
                return 0;
            }
        }
        else
        {
            return 0;
        }
    }
    catch 
    {
        throw;
    }
    finally
    {
    }
}

public string GetCompanyName()
{
    try
    {
        if (txtAutoCompleteforCompany.Text.Trim() != String.Empty)
        {
            return txtAutoCompleteforCompany.Text.Trim();
        }
        else
        {
            return string.Empty;
        }
    }
    catch
    {
        throw;
    }
    finally
    {

    }
}

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.

C#
protected void Page_Load(object sender, EventArgs e)
{
 RegisterClientScript();	
}
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:

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

License

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


Written By
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 4:49
professionalfredatcodeproject26-Feb-15 4:49 
GeneralRe: My vote of 5 Pin
Anuja Pawar Indore26-Feb-15 19:36
Anuja Pawar Indore26-Feb-15 19:36 
QuestionOutdated / Incomplete Pin
Member 93233398-Jul-14 13:57
Member 93233398-Jul-14 13:57 
AnswerRe: Outdated / Incomplete Pin
Anuja Pawar Indore8-Jul-14 20:12
Anuja Pawar Indore8-Jul-14 20:12 
AnswerRe: Outdated / Incomplete Pin
Anuja Pawar Indore26-Feb-15 19:36
Anuja Pawar Indore26-Feb-15 19:36 
QuestionPost the entire solution? Pin
charles92227-Jul-13 15:16
charles92227-Jul-13 15:16 
Questionthank you very much Pin
Member 269430711-Apr-13 3:51
Member 269430711-Apr-13 3:51 
AnswerRe: thank you very much Pin
Anuja Pawar Indore11-Apr-13 3:55
Anuja Pawar Indore11-Apr-13 3:55 
QuestionUnclear Pin
therealjordan4-Apr-13 8:25
therealjordan4-Apr-13 8:25 
AnswerRe: Unclear Pin
Anuja Pawar Indore4-Apr-13 9:19
Anuja Pawar Indore4-Apr-13 9:19 
QuestionError while retrieving data from service Pin
Brijesh Bhat3-Dec-12 20:31
Brijesh Bhat3-Dec-12 20:31 
AnswerRe: Error while retrieving data from service Pin
Anuja Pawar Indore4-Dec-12 1:22
Anuja Pawar Indore4-Dec-12 1:22 
GeneralRe: Error while retrieving data from service Pin
Brijesh Bhat5-Dec-12 0:25
Brijesh Bhat5-Dec-12 0:25 
GeneralRe: Error while retrieving data from service Pin
Anuja Pawar Indore5-Dec-12 2:54
Anuja Pawar Indore5-Dec-12 2:54 
GeneralRe: Error while retrieving data from service Pin
Brijesh Bhat5-Dec-12 21:50
Brijesh Bhat5-Dec-12 21:50 
GeneralRe: Error while retrieving data from service Pin
Anuja Pawar Indore5-Dec-12 21:56
Anuja Pawar Indore5-Dec-12 21:56 
QuestionGood Post Pin
Schin kulkarni.9-Oct-12 23:58
Schin kulkarni.9-Oct-12 23:58 
AnswerRe: Good Post Pin
Anuja Pawar Indore10-Oct-12 2:49
Anuja Pawar Indore10-Oct-12 2:49 
My Pleasure Smile | :)
QuestionActually it's not working? Pin
Leo Rajendra Dhakal1-Aug-12 21:57
Leo Rajendra Dhakal1-Aug-12 21:57 
AnswerRe: Actually it's not working? Pin
Anuja Pawar Indore2-Aug-12 23:59
Anuja Pawar Indore2-Aug-12 23:59 
GeneralRe: Actually it's not working? Pin
Leo Rajendra Dhakal3-Aug-12 0:48
Leo Rajendra Dhakal3-Aug-12 0:48 
GeneralRe: Actually it's not working? Pin
Anuja Pawar Indore3-Aug-12 2:38
Anuja Pawar Indore3-Aug-12 2:38 
GeneralRe: Actually it's not working? Pin
Leo Rajendra Dhakal3-Aug-12 14:00
Leo Rajendra Dhakal3-Aug-12 14:00 
Questionissue on trying the code Pin
Palavesam Pattan31-Oct-11 19:41
professionalPalavesam Pattan31-Oct-11 19:41 
AnswerRe: issue on trying the code Pin
Anuja Pawar Indore31-Oct-11 20:00
Anuja Pawar Indore31-Oct-11 20: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.