In this article I will explain with an example, how to search data in GridView with paging on TextBox KeyPress using jQuery in ASP.Net with C# and VB.Net.
 
 

Database

Here I am making use of Microsoft’s Northwind Database. You can download it from here.
 
 

Stored Procedure

The following Stored Procedure which will perform search and pagination on the table records and return data for each page.
CREATE PROCEDURE[dbo].[GetCustomers_Pager]
      @SearchTerm VARCHAR(100) = ''
      ,@PageIndex INT 1
      ,@PageSize INT 10
      ,@RecordCount INT OUTPUT
AS
BEGIN
      SET NOCOUNT ON;
      SELECT ROW_NUMBER() OVER
      (
            ORDER BY [CustomerID] ASC
      )AS RowNumber
          ,[CustomerID]
          ,[CompanyName]
          ,[ContactName]
          ,[City]
      INTO #Results
      FROM [Customers]
      WHERE [ContactName] LIKE @SearchTerm + '%' OR @SearchTerm = ''
      SELECT @RecordCount = COUNT(*)
      FROM #Results
          
      SELECT * FROM #Results
      WHERE RowNumber BETWEEN (@PageIndex-1) * @PageSize + 1 AND (((@PageIndex-1) * @PageSize+1) + @PageSize) -1
    
      DROP TABLE #Results
END
 
 

HTML Markup

The HTML Markup consists of following controls:
TextBox – For capturing user input.
GridView – For displaying data.
The GridView consist of three BoundField columns.
DIV – For displaying Pager.
Search:
<asp:TextBox ID="txtSearch" runat="server" />
<hr />
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="CustomerID" HeaderText="Customer Id" />
        <asp:BoundField DataField="ContactName" HeaderText="Name" />
        <asp:BoundField DataField="City" HeaderText="City" />
    </Columns>
</asp:GridView>
<br />
<div class="Pager"></div>
 
 

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
 
 

Populating GridView Dummy with Dummy Data in ASP.Net

First, global PageSize variable is created which is set to 5.
Inside the Page Load event handler, the BindDummyRow method (explained later) is called.
 
BindDummyRow
Inside the BindDummyRow method, a DataTable is created with no records and assigned to the DataSource property of the GridView and the GridView is populated.
Note: For more details on how to create DataTable with dummy records, please refer my article Dynamically create DataTable and bind to GridView in ASP.Net.
 
C#
private static int PageSize = 5;
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindDummyRow();
    }
}
 
private void BindDummyRow()
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[3]
                        {
                            new DataColumn("CustomerID"),
                            new DataColumn("ContactName"),
                            new DataColumn("City")
                        });
    dt.Rows.Add();
    gvCustomers.DataSource = dt;
    gvCustomers.DataBind();
}
 
VB.Net
Private Shared PageSize As Integer = 5
Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Me.BindDummyRow()
    End If
End Sub
 
Private Sub BindDummyRow()
    Dim dt As DataTable = New DataTable()
    dt.Columns.AddRange(New DataColumn(2) { New DataColumn("CustomerID"), New DataColumn("ContactName"), New DataColumn("City")})
    dt.Rows.Add()
    gvCustomers.DataSource = dt
    gvCustomers.DataBind()
End Sub
 
 

WebMethod to handle jQuery AJAX calls

The GetCustomers WebMethod accepts the TextBox value and PageIndex as a parameter.
Inside this WebMethod, an object of SqlCommand class is created and the searched text, PageIndex and PageSize as parameter.
The RecordCount is also passed as parameter with Data Type specified and its Direction is set to Output since by default the Direction of all parameters are Input.
Finally, the GetData method (explained later) is called which accepts SqlCommand class object and PageIndex as parameter.
 

GetData

Inside the GetData method, the Stored Procedure is executed and the fetched records are stored into a DataTable.
The DataTable is added to the DataSet and the DataSet is returned.
C#
[WebMethod]
public static string GetCustomers(string searchTerm, int pageIndex)
{
    string spName "GetCustomers_Pager";
    using (SqlCommand cmd = new SqlCommand(spName))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@SearchTerm", searchTerm);
        cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
        cmd.Parameters.AddWithValue("@PageSize", PageSize);
        cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
        return GetData(cmd, pageIndex).GetXml();
    }
}
 
private static DataSet GetData(SqlCommand cmdint pageIndex)
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            sda.SelectCommand cmd;
            using (DataSet ds = new DataSet())
            {
                sda.Fill(ds, "Customers");
                DataTable dt = new DataTable("Pager");
                dt.Columns.AddRange(new DataColumn[3]
                        {
                            new DataColumn("PageIndex"),
                            new DataColumn("PageSize"),
                            new DataColumn("RecordCount")
                       });
                dt.Rows.Add(pageIndex, PageSize,cmd.Parameters["@RecordCount"].Value);
                ds.Tables.Add(dt);
                return ds;
            }
        }
    }
}
 
VB.Net
<WebMethod>
Public Shared Function GetCustomers(ByVal searchTerm As StringByVal pageIndex As Integer) As String
    Dim spName As String "GetCustomers_Pager"
    Using cmd As SqlCommand = New SqlCommand(spName)
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.AddWithValue("@SearchTerm", searchTerm)
        cmd.Parameters.AddWithValue("@PageIndex", pageIndex)
        cmd.Parameters.AddWithValue("@PageSize", PageSize)
        cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output
        Return GetData(cmd,pageIndex).GetXml()
    End Using
End Function
 
Private Shared Function GetData(ByVal cmd As SqlCommandByVal pageIndex As Integer) As DataSet
    Dim constr As String ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Using sda As SqlDataAdapter = New SqlDataAdapter()
            cmd.Connection = con
            sda.SelectCommand cmd
            Using  ds As DataSet = New DataSet()
                sda.Fill(ds,"Customers")
                Dim  dt As DataTable = New DataTable("Pager")
                dt.Columns.AddRange(New DataColumn(2) { New DataColumn("PageIndex"), New DataColumn("PageSize"), New DataColumn("RecordCount")})
                dt.Rows.Add(pageIndex, PageSize,cmd.Parameters("@RecordCount").Value)
                ds.Tables.Add(dt)
                Return ds
            End Using
        End Using
    End Using
End Function
 
 

Client-Side Implementation

Inside the HTML Markup, the following script file is inherited.
1. jquery.min.js
2. ASPSnippets_Pager.min.js
Inside the jQuery document ready event handler, the GetCustomers JavaScript function (explained later) is called which accepts page PageIndex as a parameter which populates GridView initially with dummy data.
The GetCustomers function (explained later) is called inside the KeyUp event handler which is assigned to the TextBox and the click event handler assigned to the HTML DIV.
 

GetCustomers

Inside the GetCustomers method, a jQuery AJAX call is made to the GetCustomers WebMethod and the returned data is processed inside the OnSuccess function which refreshes the GridView with filtered data.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="ASPSnippets_Pager.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        GetCustomers(1);
 
        $("[id*= txtSearch]").keyup(function () {
            GetCustomers(parseInt(1));
        });
 
        $(".Pager").on("click",  ".page"function () {
            GetCustomers(parseInt($(this).attr('page')));
        });
    });
 
    function SearchTerm() {
        return jQuery.trim($("[id*= txtSearch]").val());
    };
 
    function GetCustomers(pageIndex) {
        $.ajax({
             type: "POST",
             url: "Default.aspx/GetCustomers",
             data: '{searchTerm: "'  + SearchTerm() + '",pageIndex: '  + pageIndex  + '}',
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             success: OnSuccess,
             failure: function (response) {
                alert(response.d);
             },
             error: function (response) {
                alert(response.responseText);
             }
        });
    };
 
    var row;
    function OnSuccess(response) {
        var xmlDoc $.parseXML(response.d);
        var xml = $(xmlDoc);
        var customers = xml.find("Customers");
        if  (row == null) {
            row = $("[id*=gvCustomers]tr:last-child").clone(true);
        }
        $("[id*= gvCustomers] tr").not($("[id*= gvCustomers]tr:first-child")).remove();
        if (customers.length > 0) {
            $.each(customers, function () {
                $("td", row).eq(0).html($(this).find("CustomerID").text());
                $("td", row).eq(1).html($(this).find("ContactName").text());
                $("td", row).eq(2).html($(this).find("City").text());
                $("[id*=gvCustomers]").append(row);
                row = $("[id*= gvCustomers]tr:last-child").clone(true);
            });
            var pager = xml.find("Pager");
            $(".Pager").ASPSnippets_Pager({
                 ActiveCssClass: "current",
                 PagerCssClass: "pager",
                 PageIndex: parseInt(pager.find("PageIndex").text()),
                 PageSize: parseInt(pager.find("PageSize").text()),
                 RecordCount: parseInt(pager.find("RecordCount").text())
            });
 
            $(".ContactName").each(function () {
                var searchPattern = new RegExp('(' + SearchTerm() + ')', 'ig');
                $(this).html($(this).text().replace(searchPattern, "" + SearchTerm() + ""));
            });
         }else {
            var empty_row  row.clone(true);
            $("td:first-child",empty_row).attr("colspan", $("td", row).length);
            $("td:first-child",empty_row).attr("align","center");
            $("td:first-child",empty_row).html("No records found for the search criteria.");
            $("td",empty_row).not($("td:first-child",empty_row)).remove();
            $("[id*= gvCustomers]").append(empty_row);
        }
    };
</script>
 
 

CSS Class

Below is the necessary CSS styles which you need to put on your page.
<style type="text/css">
    body {
        font-family:Arial;
        font-size:10pt;
    }
 
    table {
        border:1px solid #ccc;
    }
 
    table th {
        background-color:#F7F7F7;
        color:#333;
        font-weight:bold;
    }
 
    table th, table td {
        padding:5px;
        border-color:#ccc;
    }
 
    .Pager span {
        color:#333;
        background-color:#F7F7F7;
        font-weight:bold;
        text-align:center;
        display:inline-block;
        width:20px;
        margin-right:3px;
        line-height:150%;
        border:1px solid #ccc;
    }
 
    .Pager a {
        text-align:center;
        display:inline-block;
        width:20px;
        border:1px solid #ccc;
        color:#fff;
        color:#333;
        margin-right:3px;
        line-height:150%;
        text-decoration:none;
    }
 
    .highlight {
        background-color:#FFFFAF;
    }
</style>
 
 

Screenshot

Search GridView with Paging on TextBox KeyPress using jQuery in ASP.Net
 
 

Demo

 
 

Downloads