Implement jQuery AutoComplete TextBox inside ASP.Net GridView EditItemTemplate using C# and VB.Net

Last Reply 2 months ago By dharmendr

Posted 2 months ago

How to create autocomplete inside gridview in asp.net jquery ajax

I tried to create autocomplete text on textbox inside gridview using asp.net c# jquery but the autocomplete does not fire on grid

<asp:GridView ID="gvProducts" AutoGenerateColumns="False" EmptyDataText="No data available."
    runat="server" DataKeyNames="t_id" Width="100%" CssClass="table" HeaderStyle-BackColor="#ccccff"
    OnRowEditing="gvProducts_RowEditing" OnRowCancelingEdit="gvProducts_RowCancelingEdit"
    OnRowCommand="gvProducts_RowCommand" OnRowUpdating="gvProducts_RowUpdating" OnRowDeleting="gvProducts_RowDeleting">
    <Columns>
        <asp:BoundField DataField="t_date" HeaderText="Date" ReadOnly="true" Visible="false" />
        <asp:TemplateField HeaderText="Number" Visible="false">
            <ItemTemplate>
                <asp:Label ID="lb_t_id" runat="server" Text='<%#Eval("t_id")%>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Debit">
            <ItemTemplate>
                <%#Eval("t_acc")%></ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txtDebit" runat="server" Text='<%#Eval("t_acc")%>' Width="100%" />
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="txtNewDebit" runat="Server" Width="100%" />
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="btnedit" runat="server" CommandName="Edit" Text="Edit" />
            </ItemTemplate>
            <EditItemTemplate>
                <asp:LinkButton ID="btnupdate" runat="server" CommandName="Update" Text="Update" />
                <asp:LinkButton ID="btncancel" runat="server" CommandName="Cancel" Text="Cancel" />
                <asp:LinkButton ID="btnDelete" runat="server" CommandName="Delete" Text="Delete" />
            </EditItemTemplate>
            <FooterTemplate>
                <asp:Button ID="btnInsert" runat="Server" Text="Insert" CommandName="Insert" UseSubmitBehavior="False" />
            </FooterTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

 

$(function () {
    $("[id*=txtDebit]").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '<%=ResolveUrl("~/trans.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);
                }
            });
        },
        minLength: 1
    });
});

 

Posted 2 months ago Modified on 2 months ago

Hi tex,

Check this example. Now please take its reference and correct your code.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

HTML

<asp:GridView ID="gvProducts" runat="server" EmptyDataText="No data available." AutoGenerateColumns="false"
    DataKeyNames="Id" OnRowEditing="gvProducts_RowEditing" OnRowCancelingEdit="gvProducts_RowCancelingEdit"
    OnRowCommand="gvProducts_RowCommand" OnRowUpdating="gvProducts_RowUpdating" OnRowDeleting="gvProducts_RowDeleting">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="true" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:TemplateField HeaderText="Country">
            <ItemTemplate>
                <%#Eval("Country")%>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txtCountry" runat="server" Text='<%#Eval("Country")%>' />
                <asp:HiddenField ID="hfCountry" runat="server" />
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="btnedit" runat="server" CommandName="Edit" Text="Edit" />
                <asp:LinkButton ID="btnDelete" runat="server" CommandName="Delete" Text="Delete" />
            </ItemTemplate>
            <EditItemTemplate>
                <asp:LinkButton ID="btnupdate" runat="server" CommandName="Update" Text="Update" />
                <asp:LinkButton ID="btncancel" runat="server" CommandName="Cancel" Text="Cancel" />
            </EditItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js"></script>
<link rel="Stylesheet" type="text/css" href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" />
<script type="text/javascript">
    $(function () {
        $("[id*=txtCountry]").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("~/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>

Namespaces

C#

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;

VB.Net

Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Services

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        BindGridView();
    }
}

private void BindGridView()
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
    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");
    gvProducts.DataSource = dt;
    gvProducts.DataBind();
}

[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();
}

protected void gvProducts_RowEditing(object sender, GridViewEditEventArgs e)
{
    gvProducts.EditIndex = e.NewEditIndex;
    BindGridView();
}

protected void gvProducts_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    gvProducts.EditIndex = -1;
    BindGridView();
}

protected void gvProducts_RowCommand(object sender, GridViewCommandEventArgs e)
{

}

protected void gvProducts_RowDeleting(object sender, GridViewDeleteEventArgs e)
{

}

protected void gvProducts_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        BindGridView()
    End If
End Sub

Private Sub BindGridView()
    Dim dt As DataTable = New DataTable()
    dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id"), New DataColumn("Name"), New DataColumn("Country")})
    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")
    gvProducts.DataSource = dt
    gvProducts.DataBind()
End Sub

<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

Protected Sub gvProducts_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
    gvProducts.EditIndex = e.NewEditIndex
    BindGridView()
End Sub

Protected Sub gvProducts_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
    gvProducts.EditIndex = -1
    BindGridView()
End Sub

Protected Sub gvProducts_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
End Sub

Protected Sub gvProducts_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
End Sub

Protected Sub gvProducts_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
End Sub

Screenshot