Tuesday, May 4, 2010

How to use autocomplete extender in AJAX toolkit

Drag and drop a textbox in asp.net page and then wired your textbox with a autocomplete extender like below:

<div id="siteSearch">
<br />
<asp:TextBox ID="searchAutoCompleteTextBox" runat="server" CssClass="textBoxStyle"></asp:TextBox>
<div id="divwidth">
</div>
<ajaxControlToolkit:AutoCompleteExtender ID="searchAutoCompleteTextBox_AutoCompleteExtender"
runat="server" DelimiterCharacters="" Enabled="True" ServicePath="~/assets/services/autoComplete.asmx"
ServiceMethod="GetCompletionList" MinimumPrefixLength="1" EnableCaching="true"
TargetControlID="searchAutoCompleteTextBox" CompletionListCssClass="AutoExtender"
CompletionListItemCssClass="AutoExtenderList" CompletionListHighlightedItemCssClass="AutoExtenderHighlight"
CompletionListElementID="divwidth">
</ajaxControlToolkit:AutoCompleteExtender>
</div>


Then add a web service and with the following method. Please note that the return type, params should be same as the following otherwise the autocomplete will nto work. You can only change the name of the method name:


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

/// <summary>
/// Summary description for autoComplete
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class autoComplete : System.Web.Services.WebService {

public autoComplete () {

//Uncomment the following line if using designed components
//InitializeComponent();
}

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string[] GetCompletionList(string prefixText, int count)
{
string[] suggestions = new string[10];

DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("~/App_Data/AcademicUnitHierarchy.xml"));
DataView collegeDV = ds.Tables[0].DefaultView;
collegeDV.RowFilter = "h2=0 and acad_status=0";
for (int i = 0; i < 10; i++)
{
suggestions[i] = collegeDV[i]["name"].ToString();
}
return suggestions;
}
}


No comments:

Post a Comment