How to create auto complete extender with use of AJAX in ASP.NET?


In this article I have explained about how to create auto complete extender control using AJAX Auto complete Extender. For example if we type any country first letter in the textbox, it matches with database country field value and return extender with similar names for help to user select the country name from the extender.

Description
AJAX Autocomplete extender is help to user for select a value without typing all text (whole word) in the textbox control. This tool is user friendly for selecting values.
Client side
Placed one auto complete extender in the client side and set its attributes etc.

  
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="WebService.asmx" />
</Services>
</asp:ToolkitScriptManager>
Enter Country Name
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender runat="server" ID="autoComplete1" TargetControlID="TextBox1"
ServicePath="WebService.asmx" ServiceMethod="GetCountry" MinimumPrefixLength="1"
EnableCaching="true" CompletionListCssClass="Extender" CompletionListItemCssClass="ExtenderList"
CompletionListHighlightedItemCssClass="Highlight" CompletionListElementID="width" />

Below poperties are used in the Auto Complete Extender

ServicePath: It is used to set path of your webservices file.

ServiceMethod: It is used to set Service Method of your autocomplete extender. That method is available in the webservice file.

CompletionListCssClass and CompletionListItemCssClass: It is used to set css for your extender.

TargetControlID: Target control ID is used to set target of autocomplete extender i.e. if user click country name in the extender that selected value is assigned to the target control id.

In the above code I have call one webservice, so create one webservice file name as "WebService.asmx" in the App_Code folder
Create ServiceMethod "GetCountry" in that webservice file.

[WebMethod]
public string[] GetCountry(string prefixText)
{
//Retieve connection string from config file and assigned in to the sqlconnection
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
SqlCommand sqlcmd = new SqlCommand();
DataSet ds = new DataSet();
//write query to get country name based on user entered text
string query = "select country from cntryname where country like '" + prefixText + "%' ";
sqlcmd = new SqlCommand(query, sqlcon);
sqlcon.Open();
SqlDataAdapter da= new SqlDataAdapter();
da.SelectCommand = sqlcmd;
da.Fill(ds);
//Create one array variable and set size based on return datatable row count
string[] cname = new string[ds.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
//assign each value in to the array variable
cname.SetValue(dr["country"].ToString(), i);
i++;
}
}
catch(Exception ex)
{
}
finally
{
sqlcon.Close();
}
//Lastreturn that array values for bind in extender
return cname;
}

That's all after you create web service method your web page is show extender in your specified text box.

Complete Code



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AJAX Auto Complete Extender</title>
<style>
.Extender
{
font-family: Verdana, Helvetica, sans-serif;
font-size: 10px;
font-weight: normal;
border: solid 1px #006699;
line-height: 20px;
padding: 1px;
background-color: White;
}
.ExtenderList
{
border-bottom: 1px #006699;
cursor: pointer;
color: black;
}
.Highlight
{
color: White;
background-color: #229603;
cursor: pointer;
}
#width
{
width: 180px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="WebService.asmx" />
</Services>
</asp:ToolkitScriptManager>
Enter Country Name
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender runat="server" ID="autoComplete1" TargetControlID="TextBox1"
ServicePath="WebService.asmx" ServiceMethod="GetCountry" MinimumPrefixLength="1"
EnableCaching="true" CompletionListCssClass="Extender" CompletionListItemCssClass="ExtenderList"
CompletionListHighlightedItemCssClass="Highlight" CompletionListElementID="width" />
</div>
</form>
</body>
</html>

Webservice Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

///
/// Summary description for WebService
///

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
public WebService () {
}

[WebMethod]
public string[] GetCountry(string prefixText)
{
//Retieve connection string from config file and assigned in to the sqlconnection
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
SqlCommand sqlcmd = new SqlCommand();
DataSet ds = new DataSet();
//write query to get country name based on user entered text
string query = "select country from cntryname where country like '" + prefixText + "%' ";
sqlcmd = new SqlCommand(query, sqlcon);
sqlcon.Open();
SqlDataAdapter da= new SqlDataAdapter();
da.SelectCommand = sqlcmd;
da.Fill(ds);
//Create one array variable and set size based on return datatable row count
string[] cname = new string[ds.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
//assign each value in to the array variable
cname.SetValue(dr["country"].ToString(), i);
i++;
}
}
catch(Exception ex)
{
}
finally
{
sqlcon.Close();
}
//Lastreturn that array values for bind in extender
return cname;
}
}

Output:
Output of the above code look like this

Ouput

Source code:
Download the attached source code and try to learn AJAX Auto complete Extender and its uses.

Front End: ASP.NET

Code Behind: C#

Conclusion:
I hope this article is help to know about AJAX Auto complete extender in ASP.NET.


Attachments

  • Source_Code (43207-21050-AJAXAutoComplete.rar)
  • Comments

    Author: DDK08 May 2012 Member Level: Silver   Points : 0

    Hi Ravi,

    Please send me this code in zip folder on my mail id.


    Regards,
    Asha Bhatt

    Author: Laxmikant23 Jul 2012 Member Level: Gold   Points : 1

    If you do not want to create the web service. You can write the same code which you have written in web service to code behind of aspx page by using [WebMethod] attribute to the function.

    And set the pagemethods=true for script manager control



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: