How to create auto complete textbox using AJAX controls
Auto Complete is an AJAX extender that can be attached to any text box, and will inherit that control with a popup panel to display list of words that begin with the prefix typed into the text box.Suppose we wrote letter "A" in the text box then AJAX control will suggest all the word starting with letter "A" using a web service. It will call a web service for this functionality.
AutoComplete is an AJAX extender that can be attached to any textbox, and will inherit that control with a popup panel to display list of words that begin with the prefix typed into the textbox.
Suppose we wrote letter "A" in the text box then AJAX control will suggest all the word starting with letter "A" using a web service. It will call a web service for this functionality.
AJAX autocomplete properties
<asp:AutoCompleteExtender ID="AutoCompleteExtender1"
runat="server"
TargetControlID="textCity"
MinimumPrefixLength="1"
EnableCaching="true"
CompletionSetCount="1"
CompletionInterval="900"
ServiceMethod="cityname"
</asp:AutoCompleteExtender>
In the database just create a table with 2 columns- cityid and cityname for demonstration.
Add below AJAX assembly reference at the start of the page (demo.aspx)
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
So the first 2 line of demo.aspx will be like below-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="demo.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
And the body of the page will be like below-
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:TextBox ID="textCity" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="textCity"
MinimumPrefixLength="1" EnableCaching="true" CompletionSetCount="1" CompletionInterval="9000"
ServiceMethod="cityname" >
</asp:AutoCompleteExtender>
</div>
</form>
</body>
Now just create a web method in demo.aspx.cs
public static List<string> cityname(string txt)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("select * from city where cityname like @city+'%'", con);
cmd.Parameters.AddWithValue("@city", txt);
SqlDataAdapter sad = new SqlDataAdapter(cmd);
sad.Fill(dt);
List<string> citynames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
citynames.Add(dt.Rows[i][1].ToString());
}
return citynames;
}
And add the below web services so that it will support the above functionality-
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]