Tuesday, June 26, 2012

how to use AutoCompleteExtender


Step 1 : Take a TextBox , AutoCompleteExtender

<asp:TextBox runat="server" ID="txtInput" Width="300" />
<cc1:AutoCompleteExtender runat="server" ID="AutoComplete1"
TargetControlID="txtInput"
ServiceMethod="GetNames"
ServicePath="WebService.asmx"
MinimumPrefixLength="1"
CompletionInterval="1000"
EnableCaching="true"
CompletionSetCount="20"/>

Step 2 : Add ScriptManager on page with tag

<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
  <asp:ServiceReference Path="~/WebService.asmx" />
Services>
asp:ScriptManager>

Step 3: Add a Webservice file in your website by Right click on website->Add new Item ->Web Service and add this code inside it..

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

[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[] GetNames(string prefixText, int count)
  {
    List<string> items = new List<string>(count);
    DataSet ds = new DataSet();

    string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    using (SqlConnection connection = new SqlConnection(cs))
    {
        string sql = "SELECT name FROM people WHERE name LIKE '" + prefixText + "%'";
      SqlDataAdapter adapter = new SqlDataAdapter();
      adapter.SelectCommand = new SqlCommand(sql, connection);
      adapter.Fill(ds);
    }

    foreach (DataRow dr in ds.Tables[0].Rows)
    {
      items.Add(dr["name"].ToString());
    }

    return items.ToArray();
  }
}

No comments:

Post a Comment