Auto Complete TextBox using Ajax in ASP.Net

Autocomplete is an Ajax extender that searches the text from web service when you enter some text into textbox. (Web service returns random words which start from you type into the textbox).

Below is an example, how to use it.

Step: 1 you need to register Ajax Control Toolkit DLL first.

Step: 2 write the below code in .aspx page


<asp:TextBox ID="txtProductName" runat="server" AutoPostBack="True" OnTextChanged="txtProductName_TextChanged">asp:TextBox>
                <cc1:AutoCompleteExtender ID="AutoCompleteExtender1" TargetControlID="txtProductName"  MinimumPrefixLength="1"  ServiceMethod="GetCountryInfo" ServicePath="productMaster.asmx" runat="server">
        cc1:AutoCompleteExtender>
Step: 3 create web service (.asmx) page to write the code to use in Auto Complete

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.SqlClient;
using System.Data;


///


/// Summary description for productMaster
///

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService] //add this line to tun script service
public class productMaster : System.Web.Services.WebService {

SqlConnection dbcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connString"].ToString());
public productMaster () {

//Uncomment the following line if using designed components
//InitializeComponent();
}


//imp to write [WebMethod] to access the web service method
[WebMethod]
public string[] GetCountryInfo(string prefixText)
{

string sqlQry = "SELECT productName FROM product_master WHERE productname like @prefixText";

SqlDataAdapter da = new SqlDataAdapter(sqlQry, dbcon);

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

DataTable dt = new DataTable();

da.Fill(dt);

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

for (int i = 0; i < dt.Rows.Count; i++)
{
products.SetValue(dt.Rows[i]["productName"].ToString(), i);
}
return products;
}
}

Step: 4 Write below code in .aspx.cs

protected void txtProductName_TextChanged(object sender, EventArgs e)
{
AutoCompleteExtender1.ContextKey = txtProductName.Text;
}

Step: 5 now you are finished run and see the output

Comments