How to use autocompleteTextbox in Ajax

It is easier for user searching a text when you enter some text, the all text begin with with that text will show so that you can chose it and go for searching.the type of thing is used by google seach,wikimapedia etc.i have used in my project.

First you have install ajaxtoolkit ,add reference of it in your application.

ADD ScriptManager then add a textbox.

Drag and drop AutoCompleteExtender from it then the code will be like this
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>

<body>

    <form id="form1" runat="server">

    <div>

      <asp:ScriptManager ID="ScriptManager1" EnablePageMethods=true runat="server">

        </asp:ScriptManager>

    <asp:TextBox ID="txt1" runat=server ></asp:TextBox>

  

    <cc1:AutoCompleteExtender

    runat="server"

    ID="autoComplete1"

    TargetControlID="txt1"//target control

    ServiceMethod="Getdata"//method should be pagemethod

    MinimumPrefixLength="1" //minimum character for showing data

    CompletionInterval="100"//completioninterval

    EnableCaching="true"

    CompletionSetCount="20"

     >

      

</cc1:AutoCompleteExtender>

     

    </div>

    </form>

</body>
Then goto serverside

add namespace
using System.Web.Services;
But reference for webservice added before if not then add first.

Write function for getting data
[WebMethod]//MUST BE USED BEFORE FUNCTION

//METHOD MUST BE STATIC

           public static string[] Getdata(string text, int count)

          {

          

                      string sql = "Select name from  L_PHYSICALEXAM Where name like @text";

            SqlConnection conn = new SqlConnection( your connection string);

            SqlDataAdapter da = new SqlDataAdapter(sql,conn);

           

            da.SelectCommand.Parameters.Add("@prefixText", SqlDbType.VarChar, 50).Value = text+ "%";

            DataTable dt = new DataTable();

            try

            {

                da.Fill(dt);

            }

            catch(System.Exception er)

            {

                string st = er.ToString();

            }

         

            string[] items = new string[dt.Rows.Count];

            int i = 0;

            foreach (DataRow dr in dt.Rows)

            {

               items.SetValue(dr["Name"].ToString(),i);

  i++;             }

            return items;

          

        }
When you enter first character it will start show those data starting from that character from database.

Comments