Click here to Skip to main content
11,642,233 members (65,718 online)
Click here to Skip to main content

Using AJAX AutoCompleteExtender for autosuggest

, 11 Sep 2012 CPOL 90.1K 3.7K 32
Rate this:
Please Sign up or sign in to vote.
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.

[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:

 <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:

<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
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.

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:

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

Share

About the Author

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

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
fredatcodeproject26-Feb-15 4:49
memberfredatcodeproject26-Feb-15 4:49 
GeneralRe: My vote of 5 Pin
Anuja Pawar Indore26-Feb-15 19:36
memberAnuja Pawar Indore26-Feb-15 19:36 
QuestionOutdated / Incomplete Pin
Member 93233398-Jul-14 13:57
memberMember 93233398-Jul-14 13:57 
AnswerRe: Outdated / Incomplete Pin
Anuja Pawar Indore8-Jul-14 20:12
memberAnuja Pawar Indore8-Jul-14 20:12 
AnswerRe: Outdated / Incomplete Pin
Anuja Pawar Indore26-Feb-15 19:36
memberAnuja Pawar Indore26-Feb-15 19:36 
QuestionPost the entire solution? Pin
charles92227-Jul-13 15:16
membercharles92227-Jul-13 15:16 
Questionthank you very much Pin
Member 269430711-Apr-13 3:51
memberMember 269430711-Apr-13 3:51 
AnswerRe: thank you very much Pin
Anuja Pawar Indore11-Apr-13 3:55
memberAnuja Pawar Indore11-Apr-13 3:55 
QuestionUnclear Pin
therealjordan4-Apr-13 8:25
membertherealjordan4-Apr-13 8:25 
There is no explanation as to why the onblur() event of the textbox is mentioned in this article and yet does not appear in the source code. It is causing an error for me in my application. there also isn't any of the javascript in the source code.
AnswerRe: Unclear Pin
Anuja Pawar Indore4-Apr-13 9:19
memberAnuja Pawar Indore4-Apr-13 9:19 
QuestionError while retrieving data from service Pin
Member 82151053-Dec-12 20:31
memberMember 82151053-Dec-12 20:31 
AnswerRe: Error while retrieving data from service Pin
Anuja Pawar Indore4-Dec-12 1:22
memberAnuja Pawar Indore4-Dec-12 1:22 
GeneralRe: Error while retrieving data from service Pin
Brijesh Bhat5-Dec-12 0:25
memberBrijesh Bhat5-Dec-12 0:25 
GeneralRe: Error while retrieving data from service Pin
Anuja Pawar Indore5-Dec-12 2:54
memberAnuja Pawar Indore5-Dec-12 2:54 
GeneralRe: Error while retrieving data from service Pin
Brijesh Bhat5-Dec-12 21:50
memberBrijesh Bhat5-Dec-12 21:50 
GeneralRe: Error while retrieving data from service Pin
Anuja Pawar Indore5-Dec-12 21:56
memberAnuja Pawar Indore5-Dec-12 21:56 
QuestionGood Post Pin
sachin_ kulkarni9-Oct-12 23:58
membersachin_ kulkarni9-Oct-12 23:58 
AnswerRe: Good Post Pin
Anuja Pawar Indore10-Oct-12 2:49
memberAnuja Pawar Indore10-Oct-12 2:49 
QuestionActually it's not working? Pin
creatives.system1-Aug-12 21:57
membercreatives.system1-Aug-12 21:57 
AnswerRe: Actually it's not working? Pin
Anuja Pawar Indore2-Aug-12 23:59
memberAnuja Pawar Indore2-Aug-12 23:59 
GeneralRe: Actually it's not working? Pin
creatives.system3-Aug-12 0:48
membercreatives.system3-Aug-12 0:48 
GeneralRe: Actually it's not working? Pin
Anuja Pawar Indore3-Aug-12 2:38
memberAnuja Pawar Indore3-Aug-12 2:38 
GeneralRe: Actually it's not working? Pin
creatives.system3-Aug-12 14:00
membercreatives.system3-Aug-12 14:00 
Questionissue on trying the code Pin
palvesh31-Oct-11 19:41
memberpalvesh31-Oct-11 19:41 
AnswerRe: issue on trying the code Pin
Anuja Pawar Indore31-Oct-11 20:00
memberAnuja Pawar Indore31-Oct-11 20:00 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150731.1 | Last Updated 11 Sep 2012
Article Copyright 2011 by Anuja Pawar Indore
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid