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

Using AJAX AutoCompleteExtender for autosuggest

, 11 Sep 2012 CPOL
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
Follow on   Twitter

Comments and Discussions

 
QuestionOutdated / Incomplete PinmemberMember 93233398-Jul-14 14:57 
AnswerRe: Outdated / Incomplete PinmemberAnuja Pawar Indore8-Jul-14 21:12 
QuestionPost the entire solution? Pinmembercharles92227-Jul-13 16:16 
Questionthank you very much PinmemberMember 269430711-Apr-13 4:51 
AnswerRe: thank you very much PinmemberAnuja Pawar Indore11-Apr-13 4:55 
QuestionUnclear Pinmembertherealjordan4-Apr-13 9:25 
AnswerRe: Unclear PinmemberAnuja Pawar Indore4-Apr-13 10:19 
QuestionError while retrieving data from service PinmemberMember 82151053-Dec-12 21:31 
AnswerRe: Error while retrieving data from service PinmemberAnuja Pawar Indore4-Dec-12 2:22 
GeneralRe: Error while retrieving data from service PinmemberBrijesh Bhat5-Dec-12 1:25 
GeneralRe: Error while retrieving data from service PinmemberAnuja Pawar Indore5-Dec-12 3:54 
GeneralRe: Error while retrieving data from service PinmemberBrijesh Bhat5-Dec-12 22:50 
GeneralRe: Error while retrieving data from service PinmemberAnuja Pawar Indore5-Dec-12 22:56 
QuestionGood Post Pinmembersachin_ kulkarni10-Oct-12 0:58 
AnswerRe: Good Post PinmemberAnuja Pawar Indore10-Oct-12 3:49 
QuestionActually it's not working? Pinmembercreatives.system1-Aug-12 22:57 
AnswerRe: Actually it's not working? PinmemberAnuja Pawar Indore3-Aug-12 0:59 
GeneralRe: Actually it's not working? Pinmembercreatives.system3-Aug-12 1:48 
GeneralRe: Actually it's not working? PinmemberAnuja Pawar Indore3-Aug-12 3:38 
GeneralRe: Actually it's not working? Pinmembercreatives.system3-Aug-12 15:00 
Questionissue on trying the code Pinmemberpalvesh31-Oct-11 20:41 
AnswerRe: issue on trying the code PinmemberAnuja Pawar Indore31-Oct-11 21:00 
QuestionMy vote of 2 PinmemberHaBiX2-Oct-11 22:21 
AnswerRe: My vote of 2 PinmemberAnuja Pawar Indore2-Oct-11 23:22 
Thanks for suggestions, will surely work on them Smile | :)

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
Web01 | 2.8.141223.1 | Last Updated 11 Sep 2012
Article Copyright 2011 by Anuja Pawar Indore
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid