In this article I will explain with an example, how to implement jQuery AutoComplete TextBox inside GridView in ASP.Net using C# and VB.Net.
The jQuery AutoComplete Plugin is applied to all the TextBoxes and the data for the jQuery AutoComplete TextBox will be populated from the SQL Server database in ASP.Net using C# and VB.Net.
 
 
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
 
 
HTML Markup
The HTML Markup consists of an ASP.Net GridView with two BoundField columns and a TemplateField column consisting of a TextBox which will be applied with jQuery AutoComplete Plugin and a HiddenField to store the value of the selected AutoComplete item.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" />
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:TextBox ID="txtCountry" runat="server" CssClass="Country" />
                <asp:HiddenField ID="hfCountry" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
 
VB.Net
Imports System.Data
Imports System.Web.Services
Imports System.Configuration
Imports System.Data.SqlClient
 
 
Binding the GridView control
Inside the Page Load event handler, the GridView is populated with a dynamic DataTable with some dummy data.
Note:You can learn more about this technique in my article Create DataTable dynamically and bind to GridView in ASP.Net.
 
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
                        new DataColumn("Name", typeof(string)),
                        new DataColumn("Country",typeof(string)) });
        dt.Rows.Add(1, "John Hammond", "United States");
        dt.Rows.Add(2, "Mudassar Khan", "India");
        dt.Rows.Add(3, "Suzanne Mathews", "France");
        dt.Rows.Add(4, "Robert Schidner", "Russia");
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As New DataTable()
        dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColumn("Country", GetType(String))})
        dt.Rows.Add(1, "John Hammond", "United States")
        dt.Rows.Add(2, "Mudassar Khan", "India")
        dt.Rows.Add(3, "Suzanne Mathews", "France")
        dt.Rows.Add(4, "Robert Schidner", "Russia")
        GridView1.DataSource = dt
        GridView1.DataBind()
    End If
End Sub
 
 
WebMethod for supplying data to jQuery AutoComplete TextBox
Inside the GetCountries WebMethod, a parameter prefix is accepted and its value is used to find matching records from the Customers Table of the Northwind database.
The select query gets the Country of the customer that matches the prefix text.
The fetched records are processed and a Key Value Pair is created by appending the fields in the following format {0}-{1}.
C#
[WebMethod]
public static string[] GetCountries(string prefix)
{
    List<string> countries = new List<string>();
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "SELECT DISTINCT Country FROM Customers WHERE Country LIKE @SearchText + '%'";
            cmd.Parameters.AddWithValue("@SearchText", prefix);
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    countries.Add(string.Format("{0}-{1}", sdr["Country"], sdr["Country"]));
                }
            }
            conn.Close();
        }
    }
 
    return countries.ToArray();
}
 
VB.Net
<WebMethod()>
Public Shared Function GetCountries(ByVal prefix As String) As String()
    Dim countries As List(Of String) = New List(Of String)()
    Using conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As SqlCommand = New SqlCommand()
            cmd.CommandText = "SELECT DISTINCT Country FROM Customers WHERE Country LIKE @SearchText + '%'"
            cmd.Parameters.AddWithValue("@SearchText", prefix)
            cmd.Connection = conn
            conn.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
 
                While sdr.Read()
                    countries.Add(String.Format("{0}-{1}", sdr("Country"), sdr("Country")))
                End While
            End Using
            conn.Close()
        End Using
    End Using
    Return countries.ToArray()
End Function
 
 
The jQuery AutoComplete implementation
The jQuery AutoComplete plugin has been applied to all the TextBoxes using CSS class name.
A jQuery AJAX call is made to the GetCountries WebMethod and the list of Countries returned from the WebMethod acts as source of data to the jQuery AutoComplete.
The data received from the server is processed in the jQuery AJAX call success event handler. A loop is executed for each received item in the list of items and then an object with text part in the label property and value part in the val property is returned.
A Select event handler has been defined for the jQuery AutoComplete and when an item is selected from the AutoComplete List, the value of the item is stored in the HiddenField.
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css"
    rel="Stylesheet" type="text/css" />
<script type="text/javascript">
    $(function () {
        $(".Country").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: 'Default.aspx/GetCountries',
                    data: "{ 'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item.split('-')[0],
                                val: item.split('-')[1]
                            }
                        }))
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            select: function (e, i) {
                $(this).parent().find("input[type=hidden]").val(i.item.val);
            },
            minLength: 1
        }).focus(function () {
            $(this).autocomplete("search");
        });
    });
</script>
 
 
Screenshot
Implement jQuery AutoComplete TextBox inside GridView in ASP.Net
 
 
Demo
 
 
Downloads