AutoComplete TextBox from DataBase


In order to use the ajax autocomplete extender we have to use an asp.net

component i.e. Webservice.asmx

This component is used to be get connect with the database.

we can get this component simply by right click on asp.net project and add new item.

By doing so an .cs file will be generated named Webservice.cs in App_Code folder.

We have to add the following webmethod in the cs class file.


public string[] GetLocationInfo(string prefixText)
{
 int count = 10;
 string sql = "Select * from Locations Where Location like @prefixText";
 SqlDataAdapter da = new SqlDataAdapter(sql,webindia.Connstring);
 da.SelectCommand.Parameters.Add("@prefixText", SqlDbType.VarChar, 50).Value = prefixText+ "%";
 DataTable dt = new DataTable();
 da.Fill(dt);
 string[] items = new string[dt.Rows.Count];
 int i = 0;
 foreach (DataRow dr in dt.Rows)
 {
  items.SetValue(dr["Location"].ToString(),i);
  i++;
 }
 return items;
}



// To allow this Web Service to be called from script, using ASP.NET AJAX,we have to add the below namespace outside the class on starting itself
 [System.Web.Script.Services.ScriptService]




In the design side we have to do the following:


<asp:TextBox Maxlength="50" id="txtname2" class="bdtxt" onblur="this.value=Trim(this.value)" onkeypress="return noNumbers(event)" runat="server"/>


 <cc1:AutoCompleteExtender CompletionListCssClass="Completer_completionListElement FS-NBK" CompletionListItemCssClass="Completer_listItem" CompletionListHighlightedItemCssClass="Completer_highlightedListItem" ID="AutoCompleteExtender1" runat="server" MinimumPrefixLength="1" ShowOnlyCurrentWordInCompletionListItem="true" ServiceMethod="GetLocationInfo" FirstRowSelected="true"  ServicePath="WebService.asmx" TargetControlID="txtname2"> </cc1:AutoCompleteExtender>
                   


And then run the project, it will work effectively