Sep 16, 2014

Posted in , , , ,

ASP.NET 4.5.2 Hosting - HostForLIFE :: ASP.NET Auto-Suggest Textbox

The AutoCompleteExtender control was used with an ASP.NET textbox. Using the ASP.NET Ajax controls makes the auto complete work very easy.

You want to make sure that one and only one ScriptManager control is on the page. Inside the ScriptManager control you want to include the web service that the AutoCompleteExtender control will be communicating with.<asp:ScriptManager ID=”ScriptManager2″ runat=”server” >
<Services>
<asp:ServiceReference Path=”MyWebService.asmx” />
</Services>
</asp:ScriptManager> 

http://www.hostforlife.eu/European-ASPNET-452-Hosting


You want to add an ASP.NET textbox control. Make sure to set theautocomplete=”false” this will prevent suggestions of what you have entered before from being shown from the browser.<asp:TextBox ID=”TextBox1″ runat=”server” CssClass=”suggestText” autocomplete=”off” />

Add the AutoCompleteExtender control. Here is an example to what I set the attributes to.
<ajaxToolkit:AutoCompleteExtender
ID=”AutoCompleteExtender2″
runat=”server”
TargetControlID=”TextBox1″ /* The textbox the extend.*/
CompletionInterval=”10″ /* How many milliseconds to wait.*/
CompletionSetCount=”10″ /* How many results to show.*/
MinimumPrefixLength=”1″ /* How many letters need to be typed.*/
ServicePath=”MyWebService.asmx” /* Path to the web service.*/
ServiceMethod=”AutoSuggest” /* The web services method.*/ />


Now create your webservice.
[WebMethod]
public string[] AutoSuggest(string prefixText, int count)
{
DataView dvStates = new DataView(clsGlobal.dtStates, string.Format(“StateName like ‘{0}%’”, prefixText), “”, DataViewRowState.CurrentRows);System.Collections.Generic.List<string> items = new System.Collections.Generic.List<string>(count);for (int i = 0; i < dvStates.Count; i++)
{
items.Add(dvStates[i]["StateName"].ToString());
}
return items.ToArray();


This webservice searches through a DataView of states where the name of the State, “StateName”, starts with the letters that the user entered. Here’s how it works:
  1. The DataView is populated from a DataTable, clsGlobal.dtStates, that gets the States from a database.
  2. A generic list is created to hold the results in an array, the count of the list is the value you specified as CompletionSetCount in the AutoCompleteExtender control.
  3. A for loop is used to loop through the results from the DataView and enters them in the array.
  4. The array is return to be loaded in the AutoCompleteExtendercontrol.

Remember the parameters for the method have to be (string prefixText, int count) or the AutoCompleteExtender will not work properly.

0 comments:

Post a Comment

thanks for your comment!