Here am explaining how you can use the AutoCompleteExtender control from ASP.NET AJAX Control Toolkit.. I have a Autocomplete Textbox which fetches data from the database and this is performed with Web service..
Place a webservice(WebService.asmx) in your AppCode folder. You need to add the ScriptService reference to your Webservice.
The Class function for the Webservice is as follows
using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
[WebService]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : WebService
{
public AutoComplete()
{
}
[WebMethod]
public string[] GetCompletionList(string prefixText, int count)
{
if (count == 0)
{
count = 10;
}
DataTable dt = GetRecords(prefixText);
List
for (int i = 0; i < dt.Rows.Count; i++)
{
string strName = dt.Rows[i][0].ToString(); items.Add(strName);
}
return items.ToArray();
}
public DataTable GetRecords(string strName)
{
string strConn = ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("@Name", strName);
cmd.CommandText = "Select Distinct YourValue from YourTable where YourValue like +@Name+'%' ";
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd; con.Open();
dAdapter.Fill(objDs);
con.Close();
return objDs.Tables[0];
}
}
The CSS for the AutoComplete looks like this.
CSS:
.AutoExtender
{
font-family: Verdana, Helvetica, sans-serif;
font-size: .8em;
margin:0px;
font-weight: normal;
border:solid 1px #006699;
line-height:20px;
padding:0px;
background-color:White;
}
.AutoExtenderList
{
border-bottom:dotted 1px #006699;
cursor:pointer;
color:Maroon;
left:auto;
margin:0px;
}
.AutoExtenderHighlight
{
color:White;
background-color:#006699;
cursor:pointer;
margin:0px;
}
And add this properties to your Autocomplete Extender
CompletionListCssClass="AutoExtender" CompletionListItemCssClass="AutoExtenderList" CompletionListHighlightedItemCssClass="AutoExtenderHighlight" BehaviorID="AutoCompleteEx" OnClientShown="ShowOptions" OnClientPopulated="BoldChildren" OnClientItemSelected="aceSelected" CompletionInterval="1" CompletionSetCount="10" TargetControlID="txtSearch" ServicePath="~/Autocomplete.asmx" ServiceMethod="GetCountriesList" MinimumPrefixLength="1" EnableCaching="true">
And finally To enable OnClientItemSelected we need to perform something like this..
Place a hiddenfield and call the event in the script as below
function GetCode(source, eventArgs)
{
$get('<%=this.HiddenField1.ClientID%>').value = eventArgs.get_value();
$get('<%=this.ImageButton1.ClientID%>').click();
}
And now your AutocompleteExtender is done