AutoComplete TextBox in ASP.Net

Introduction

In this blog we will be using the Web Method directly in the code behind.

Objective

  1. Writing the WebMethod in Code behind.
  2. Understanding AJAX Auto Complete Extender.

Required

  1. TargetControlID :- It will hold the ID of the textbox that will be used for auto-complete
  2. MinimumPrefixLength :- The count of characters required to enter by the user to fetch data from the database matching the Character.
  3. ServiceMethod :- The name of the webmethod that we have used to get data from database in the web service.(Note :- Name of the web method should be case sensitive).

HTML

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <title></title>

</head>

<body>

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

    <div>

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

        <asp:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server" DelimiterCharacters=""

            Enabled="True" ServiceMethod="GetListofCountries" MinimumPrefixLength="1" EnableCaching="true"

            ServicePath="" TargetControlID="TextBox1">

        </asp:AutoCompleteExtender>

    </div>

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

    </asp:ScriptManager>

    </form>

</body>

</html>

Code Behined
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

using System.Data;

 

public partial class Default2 : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

    }

    [System.Web.Script.Services.ScriptMethod()]

    [System.Web.Services.WebMethod]

    public static List<string> GetListofCountries(string prefixText)

    {

        using (SqlConnection sqlconn = new SqlConnection("Data Source=.;Initial Catalog=hotel;Integrated Security=True"))

        {

            sqlconn.Open();

            SqlCommand cmd = new SqlCommand("select Country from country where Country like '" + prefixText + "%' ", sqlconn);

            cmd.Parameters.AddWithValue("@Country", prefixText);

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            DataTable dt = new DataTable();

            da.Fill(dt);

            List<string> CountryNames = new List<string>();

            for (int i = 0; i < dt.Rows.Count; i++)

            {

                CountryNames.Add(dt.Rows[i]["country"].ToString());

            }

            return CountryNames;

        }

    }

}