SIGN UP MEMBER LOGIN:    
ARTICLE

Using Ajax AutoCompleteExtender For Autosuggest

Posted by Anuja Pawar Articles | AJAX in C# January 03, 2012
In the present scenario, we need our text boxes to act more user friendly and auto suggest is a feature that makes them more user friendly.
Reader Level:
Download Files:
 


Ajax.jpg

Introduction

In the present scenario, we need our text boxes to act more user friendly and auto suggest is a feature that makes them more user friendly. Moreover the chance of making typographical mistakes are also reduced. 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 a 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 the 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. TargetControlIDis 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.

Login to add your contents and source code to this article
share this article :
post comment
 

ya rlly gd , my sugg:: plz avd more code bcz .net its 80% less cde bt dt be anrg by edi any new thnk -->artedison@yahoo.com

Posted by edisonamirtharaj Mar 01, 2012

Thanks Abhi :)

Posted by Anuja Pawar Jan 05, 2012

Thanks for appreciation Daisy :)

Posted by Anuja Pawar Jan 05, 2012

Thanks Emmy :)

Posted by Anuja Pawar Jan 05, 2012

Sure Sonakshi :)

Posted by Anuja Pawar Jan 05, 2012
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Nevron Gauge for SharePoint
Become a Sponsor