Building an ASP.NET GridView with DatePicker Filter and WebMethod Dropdown

Introduction

In this tutorial, we’ll build a fully functional ASP.NET Web Forms page that displays a GridView with:

  • A date filter using DatePicker
  • A symbol dropdown list dynamically populated from a SQL table using [WebMethod]
  • Real-time filtering using AJAX calls and server-side SQL data

This use case is ideal for applications that require filtering records, such as IPO bids, transactions, or logs, based on a selected date range and company symbol.

Tools & Technologies Used

  • ASP.NET Web Forms (C#)
  • SQL Server
  • JavaScript & jQuery
  • AJAX ScriptManager
  • WebMethod ([System.Web.Services.WebMethod])

Add Connection String in Web.config

<connectionStrings>
    <add name="IPOOnline" 
         connectionString="Data Source=YourServer;Initial Catalog=YourDB;User ID=sa;Password=yourpassword;" 
         providerName="System.Data.SqlClient" />
</connectionStrings>

1) .aspx Page Markup (GridView + Filters)

<%@ Page Title="" Language="C#" MasterPageFile="~/Admin/AdminMaster.Master" EnableEventValidation="false"  AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="xyzpages.Admin.test" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <style>
        .cms-table tr th {
            text-align:center;
        }
        table.dataTable.no-footer {
            border-bottom: none !important;
        }

        .editanchor {
            cursor: pointer !important;
        }

        .displayblck {
            display: block !important;
        }

        .container {
            width: 100%!important; max-width: none !important;
        }   .cms-table th, .cms-table td {
        border: 2px solid #ddd;  
        padding: 8px;
    }
       .cms-table th {
        position: sticky;
        top: .5px;
        background: #fff;
        color: black;
        z-index: 5;
         outline: 1px solid #ddd;
     }
        .ReportHeader{
            position:sticky;
            top:-1px;
              z-index: 5;
        }  .table-bordered>tbody>tr>th{
             border:none;
         }
    </style>
    <section class="grey-bg">

       

        <div class="container">
            <div class="row">
                <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                    <div class="head-with-filer">
                        <div class="dashboard-heading">
                            <h3>Offline Order List&nbsp;&nbsp;</h3>
                        </div>
                         <div class="filter-section">
 
                              <div class="calender-section">
                                <div class="calender-inner" name="daterange">
                                    <img src="images/calender.png" alt="calender" class="img-responsive" id="calendarIcon">
                                    <span id="datevalspan" runat="server" class="date-range-display"></span>
                                    <img src="images/down-white.png" alt="down-white" class="img-responsive">
                                    <asp:HiddenField ID="hdnDateRange" runat="server" />
                                    <asp:Button ID="btnBind" runat="server" Text="Bind Date" OnClick="btnBind_Click" Style="display: none;" />
                                </div>
                            </div>

                          
                        </div>
                    </div>
                   
                    <div class="cms-table table-responsive" style="padding-top: 20px;">
                        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                            <div class="admin-select admindv">
                                <asp:DropDownList ID="drpcompany" AutoPostBack="false" runat="server">
                                    <asp:ListItem Value="" Text="Select Company Name"></asp:ListItem>
                                </asp:DropDownList>
                                <input type="text" id="datelbl" runat="server" style="display:none;" />
                            </div>
                            <div class="admin-select admindv">
                                <asp:DropDownList ID="drpCategory" AutoPostBack="false" runat="server">
                                    <asp:ListItem Value="" Text="Select Category Name"></asp:ListItem>
                                </asp:DropDownList>
                            </div>
                            <div class="admin-select admindv">
                                <asp:DropDownList ID="drpUser" AutoPostBack="false" runat="server" Width="200px">
                                    <asp:ListItem Value="" Text="Select User"></asp:ListItem>
                                </asp:DropDownList>
                            </div>
                          
                            <div class="admindv">
                                <asp:TextBox runat="server" CssClass="admin-input ValidateAlfa" ID="txtAppNo" ClientIDMode="Static" placeholder="Application No"></asp:TextBox>
                            </div>
                            <div class="admindv"  style="display:none;" >
                                <asp:TextBox runat="server" CssClass="admin-input" ID="txtBidId" ClientIDMode="Static" MaxLength="10" placeholder="Bid ID"></asp:TextBox>
                            </div>
                            <div class="admindv">
                                <asp:TextBox runat="server" CssClass="admin-input" ID="txtPAN" ClientIDMode="Static" placeholder="PAN No"></asp:TextBox>
                            </div>
                            

                               <div class="calender-section" style="margin-bottom: 5px;" onclick="validateuser();">
                                <div class="calender-inner">
                                    <span><a style="cursor: pointer;" id="btnsearch">Search</a></span>
                                </div>
                            </div>
                             <div class="admindv" style="float:right !important;">
                             <asp:ImageButton ID="imgbtn" runat="server" OnClick="btnexcel_Click"  ImageUrl="/images/excel.gif" style="cursor:pointer;float:right;"/>
                             <asp:HiddenField ID="datehdn" runat="server" />
                             <asp:HiddenField ID="symbhdn" runat="server" />
                             <asp:HiddenField ID="usrhdn" runat="server" />
                             <asp:HiddenField ID="categoryhdn" runat="server" />
                            </div>
                        </div>  <div style="position: relative; display: inline-block; float: right; margin-bottom: 10px;margin-right: 16px;">
                            <asp:TextBox ID="txtFilter" runat="server" onkeyup="filterGrid()" placeholder="Search" CssClass="serachbox" />
                            <img id="clearBtn" src="../images/close.gif" alt="Clear" style="cursor: pointer; position: absolute; right: 10px; top: 50%; transform: translateY(-50%); display: none;" onclick="clearInput()" />
                        </div>
                        <div class="cms-table" id="leadstablediv" style="overflow-y: auto; max-height: 300px; width: 100%;padding-right: 15px;
    padding-left: 15px;">
     <asp:GridView ID="GridView1" runat="server" Width="100%" AutoGenerateColumns="false"
         GridLines="None" 
         CssClass="table table-striped table-bordered cms-table" >
         <Columns>
             <asp:TemplateField HeaderText="Exchange" HeaderStyle-CssClass="gridheader-alignment" SortExpression="Exchange">
                 <ItemTemplate>
                     <asp:Label ID="lblExchange" runat="server" Text='<%#Bind("Exchange") %>'></asp:Label>
                 </ItemTemplate>
             </asp:TemplateField>
             <asp:TemplateField HeaderText="User Name" HeaderStyle-CssClass="gridheader-alignment" SortExpression="ApplicantName">
                 <ItemTemplate>
                     <asp:Label ID="lblApplicantName" runat="server" Text='<%#Bind("ApplicantName") %>'></asp:Label>
                 </ItemTemplate>
             </asp:TemplateField>
             <asp:TemplateField HeaderText="Pan" HeaderStyle-CssClass="gridheader-alignment" SortExpression="PanNo">
                 <ItemTemplate>
                     <asp:Label ID="lblPanNo" runat="server" Text='<%#Bind("PanNo") %>'></asp:Label>
                 </ItemTemplate>
             </asp:TemplateField>
             <asp:TemplateField HeaderText="Application No" HeaderStyle-CssClass="gridheader-alignment" SortExpression="appno">
                 <ItemTemplate>
                     <asp:Label ID="lblApplicationNo" runat="server" Text='<%#Bind("appno") %>'></asp:Label>
                 </ItemTemplate>
             </asp:TemplateField>
             <asp:TemplateField HeaderText="Status" HeaderStyle-CssClass="gridheader-alignment" SortExpression="Status">
                 <ItemTemplate>
                     <asp:Label ID="lblBidId" runat="server" Text='<%#Bind("Status") %>'></asp:Label>
                 </ItemTemplate>
             </asp:TemplateField>
             <asp:TemplateField HeaderText="Quantity" HeaderStyle-CssClass="gridheader-alignment" SortExpression="Quantity">
                 <ItemTemplate>
                     <asp:Label ID="lblQuantity" runat="server" Text='<%#Bind("Quantity") %>'></asp:Label>
                 </ItemTemplate>
             </asp:TemplateField>
             <asp:TemplateField HeaderText="Scrip Name" HeaderStyle-CssClass="gridheader-alignment" SortExpression="Symbol">
                 <ItemTemplate>
                     <asp:Label ID="lblSymbol" runat="server" Text='<%#Bind("Symbol") %>'></asp:Label>
                 </ItemTemplate>
             </asp:TemplateField>
             <asp:TemplateField HeaderText="Price" HeaderStyle-CssClass="gridheader-alignment" SortExpression="Rate">
                 <ItemTemplate>
                     <asp:Label ID="lblRate" runat="server" Text='<%#Bind("Rate") %>'></asp:Label>
                 </ItemTemplate>
             </asp:TemplateField>
             <asp:TemplateField HeaderText="UCC code" HeaderStyle-CssClass="gridheader-alignment" SortExpression="uccId">
                 <ItemTemplate>
                     <asp:Label ID="lbluccId" runat="server" Text='<%#Bind("uccId") %>'></asp:Label>
                 </ItemTemplate>
             </asp:TemplateField>
          <asp:TemplateField HeaderText="Action" HeaderStyle-CssClass="gridheader-alignment">
    <ItemTemplate>
        <a style="padding-left: 5px; color:#007bff;"
            href='<%# "/admin/viewissue.aspx?OffID=" + Eval("BidSrNo") + "&Exchange=" + Eval("Exchange") %>'
            target="_blank">
            <b>View</b>
        </a>
    </ItemTemplate>
</asp:TemplateField>

         </Columns>
          <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                                <HeaderStyle CssClass="ReportHeader" />
                                <RowStyle BackColor="#EFF3FB" HorizontalAlign="Left" />
                                <AlternatingRowStyle BackColor="White" HorizontalAlign="Left" />
     </asp:GridView>
                            <div id="nodatadivopen" runat="server" class="table-body" align="center"    >
                                            <asp:Label ID="lblnodatadivopen" runat="server" Style="color: red;font-size: 17px;">No Data Available !!</asp:Label>
                                        </div>
 </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <div class="modalload" style="display:none">
        <div class="centerload">
            <img alt="" src="../images/loading1.gif" />
        </div>
    </div> 
    <script type="text/javascript">
    function showLoader() {
        document.querySelector('.modalload').style.display = 'flex';
       
    }

    function hideLoader() {
        document.querySelector('.modalload').style.display = 'none';
         
    }

    // Hide the loader once the page loads completely
    window.onload = function () {
        hideLoader();
    };
</script>

    <script type="text/javascript">
        function filterGrid() {
            var input, filter, table, tr, td, i, j, txtValue;
            input = document.getElementById("<%= txtFilter.ClientID %>");

            // Show or hide the clear button based on input
            var clearBtn = document.getElementById("clearBtn");
            if (input.value) {
                clearBtn.style.display = "block"; // Show clear button
            } else {
                clearBtn.style.display = "none"; // Hide clear button
            }

            if (!input) {
                console.error("Input element not found");
                return;
            }

            filter = input.value.toUpperCase();
            table = document.getElementById("<%= GridView1.ClientID %>");
        tr = table.getElementsByTagName("tr");

        for (i = 1; i < tr.length; i++) {
            tr[i].style.display = "none"; // Hide all rows
            td = tr[i].getElementsByTagName("td");
            for (j = 0; j < td.length; j++) {
                if (td[j]) {
                    txtValue = td[j].textContent || td[j].innerText;
                    if (txtValue.toUpperCase().indexOf(filter) > -1) {
                        tr[i].style.display = ""; // Show row if match found
                        break;
                    }
                }
            }
        }
    }

    function clearInput() {
        var input = document.getElementById("<%= txtFilter.ClientID %>");
        input.value = ""; // Clear the input
        filterGrid(); // Call filterGrid to refresh the GridView
        document.getElementById("clearBtn").style.display = "none"; // Hide clear button
    }

    window.onload = function () {
        document.getElementById("<%= txtFilter.ClientID %>").onkeyup = filterGrid;
        filterGrid(); // Call initially to set button visibility
    };
         

    </script>
    <style>
        .modalload {
    position: fixed;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    top: 0;
    left: 0;
    display: none;
    justify-content: center;
    align-items: center;
    z-index: 9999;
}

.centerload img {
    width: 80px; /* Adjust as needed */
}

        
         .serachbox {
            float: right;
            padding: 8px 10px;
            border: 1px solid #ddd;
            -webkit-appearance: none;
            border-radius: 2px;
            font-size: 14px;
        }

        /*#leadstablediv {
            margin-top: 90px;
        }*/
        .colorclass {
            background: #34b350;
            padding: 7px 10px;
            border-radius: 5px;
            cursor: pointer;
            display: inline-block;
            margin-right: 10px;
            vertical-align: middle;
            font-size: 14px;
            color: #fff;
            border-color: #34b350;
        }

            .colorclass:hover {
                background: #fff;
                color: blue;
            }

        .dataTables_length {
            padding: 20px;
        }

            .dataTables_length select {
                background-color: #e8ffed;
                padding: 0 3px;
                border: 1px solid #dadada;
                border-radius: 5px;
                height: 35px;
                width: 45px;
                margin-right: 10px;
                -webkit-appearance: none;
                cursor: pointer;
            }

                .dataTables_length select::after {
                    content: "\f107";
                    font-family: FontAwesome;
                    position: absolute;
                    position: absolute;
                    right: 14px;
                    font-size: 16px;
                    top: 6px;
                    pointer-events: none;
                }

        .dataTables_filter {
            padding: 20px;
        }

            .dataTables_filter input[type="search"] {
                width: 100%;
                padding: 8px 10px;
                border: 1px solid #ddd;
                -webkit-appearance: none;
                border-radius: 2px;
                font-size: 14px;
            }
    </style>
    <script>
        $(document).ready(function () {
            Getsymbol();
            GetCategory();
            GetApplicantName();
            
            var date = new Date();
            var todate = date.toLocaleDateString('fr-CA'); //2024-10-03
            date.setMonth(date.getMonth() - 1); // - 1 month 
            var frmdate = date.toLocaleDateString('fr-CA'); // current date  2024-09-03
           
        });

        
        $(function () {
            $('div[name="daterange"]').daterangepicker({
                opens: 'right',
                dateFormat: 'dd/M/yy',
                maxDate: new Date(),
                showDropdowns: true,
                locale: {
                    format: 'DD MMM YYYY',
                    "separator": " To ",
                    "customRangeLabel": "Custom",
                },
                linkedCalendars: false,
                buttonClasses: 'colorclass',
                autoApply: true,

            }, function (start, end, label) {

              
                var appno = $("#txtAppNo").val();
                var pan = $("#txtPAN").val();
                var bidid = $("#txtBidId").val();
                var cname = $("#<%=drpcompany.ClientID%>").val();
                var category = $("#<%=drpCategory.ClientID%>").val();
                var userid = $("#<%=drpUser.ClientID%>").val();
                var test = start.format('DD MMM YYYY') + " - " + end.format('DD MMM YYYY');
                $("#<%=hdnDateRange.ClientID%>").val(test);
                $("#<%=datevalspan.ClientID%>").text(test);
                var btnBind = document.getElementById('<%= btnBind.ClientID %>');
                btnBind.click();
            });
        });
        function getdata() {
            debugger;
            var appno = $("#txtAppNo").val();
            var pan = $("#txtPAN").val();
            var bidid = $("#txtBidId").val();
            var cname = $("#<%=drpcompany.ClientID%>").val();
            var category = $("#<%=drpCategory.ClientID%>").val();
            var userid = $("#<%=drpUser.ClientID%>").val();

            // Retrieve the text value from datevalspan
            var date1 = $("#<%=datevalspan.ClientID%>").text();

            // Set the value of hdnDateRange to date1
            $("#<%=hdnDateRange.ClientID%>").val(date1);

            // Now get the value from hdnDateRange
            var dates = $("#<%=hdnDateRange.ClientID%>").val();

            // Convert dates and check the type
            var convertedDate = dateconvertion(dates);
            console.log(convertedDate); // Log to check what it returns

            if (typeof convertedDate === 'string') {
                var date = convertedDate.split('~');
              
            } else {
                console.error("Converted date is not a string:", convertedDate);
            }

            var btnBind = document.getElementById('<%= btnBind.ClientID %>');
              btnBind.click();

        }
        function formatDateToYMD(dateString) {
            //alert(dateString);
            // Split the input date string to extract year, month, and day
            const parts = dateString.split('-');
            const year = parseInt(parts[0], 10);
            const month = parseInt(parts[1], 10) - 1; // Months are 0-based in JavaScript
            const day = parseInt(parts[2], 10);

            // Create a new date object in UTC
            const date = new Date(Date.UTC(year, month, day));

            // Format it to yyyy-MM-dd
            const formattedYear = date.getUTCFullYear();
            const formattedMonth = String(date.getUTCMonth() + 1).padStart(2, '0'); // Ensure two-digit month
            const formattedDay = String(date.getUTCDate()).padStart(2, '0'); // Ensure two-digit day

            return `${formattedYear}-${formattedMonth}-${formattedDay}`;
        }
        function dateconvertion(date) {
            debugger;
            var rdate = "";
            var d = date.split('-')
            for (var i = 0; i < d.length; i++) {
                const date = new Date(d[i]);
                const year = date.getFullYear();//2024
                const month = String(date.getMonth() + 1).padStart(2, '0'); // 09  Months are 0-based
                const day = String(date.getDate()).padStart(2, '0');//03
                rdate += `${year}-${month}-${day}`;//rdate = 2024-09-03 ,yera=2024 , month=09
                if (i == 0) {
                    rdate += '~';
                }
            }
            return rdate;
        }
        function validateuser() {
            debugger;

            var pan = $("#txtPAN").val();


            if (pan != "") {
                if (pan.length < 10) {
                    alert("Please enter atleast 10 digit PAN Number.");
                    document.getElementById('txtPAN').focus();
                    return false;
                }

            }


            getdata();

        }

        $('#calendarIcon').click(function () {
            $('div[name="daterange"]').daterangepicker('show'); // Show the calendar when the calendar icon is clicked
        });
        $('#btnsearch').click(function (e) {
            e.preventDefault();
            validateuser();
        });
        function Getsymbol() {
            $.ajax({
                type: "POST",
                url: "/Admin/test.aspx/Getsymbol",
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    var drpcompany = $("[id*=drpcompany]");
                    drpcompany.empty().append('<option selected="selected" value="">All</option>');
                    $.each(r.d, function () {
                        drpcompany.append($("<option></option>").val(this['Value']).html(this['Text']));
                    });
                }
            });
        }

        function GetCategory() {
            $.ajax({
                type: "POST",
                url: "/Admin/test.aspx/GetCategory",
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    var drpCategory = $("[id*=drpCategory]");
                    drpCategory.empty().append('<option selected="selected" value="">All</option>');
                    $.each(r.d, function () {
                        drpCategory.append($("<option></option>").val(this['Value']).html(this['Text']));
                    });
                }
            });
        }

        function GetApplicantName() {
            $.ajax({
                type: "POST",
                url: "/Admin/test.aspx/GetApplicantName",
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    var drpUser = $("[id*=drpUser]");
                    drpUser.empty().append('<option selected="selected" value="">All</option>');
                    $.each(r.d, function () {
                        drpUser.append($("<option></option>").val(this['Value']).html(this['Text']));
                    });
                }
            });
        }
        function validateq()
        {
            debugger;
             var cname = $("#<%=drpcompany.ClientID%>").val();
                var category = $("#<%=drpCategory.ClientID%>").val();
            var userid = $("#<%=drpUser.ClientID%>").val();
            var datee = datevalspan.innerHTML;
            cname=datee.toString()
                
            
            document.getElementById("#<%=symbhdn.ClientID%>").value = cname;
            document.getElementById("#<%=categoryhdn.ClientID%>").value = category;
            document.getElementById("#<%=usrhdn.ClientID%>").value = userid;
            return true;
            
        }

    </script>
</asp: Content>

2) Code-Behind to Bind GridView Based on Filter

using AppBlock;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace xyzpages.Admin
{
    public partial class test: System.Web.UI.Page
    {
        string consString = ConfigurationManager.ConnectionStrings["IPOOnline"].ConnectionString;

        public string fdate = "", sdate = ""; public DataSet ds = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["adminuserid"] == null || Session["adminuserid"].ToString() == "")
            {
                Response.Redirect("/admin/Adminlogin.aspx");
            }
            if (!IsPostBack)
            {
                fdate = DateTime.Today.AddMonths(-1).ToString("dd MMM yyyy");
                sdate = DateTime.Now.ToString("dd MMM yyyy");
                datevalspan.InnerText = $"{fdate} - {sdate}";
                hdnDateRange.Value = $"{fdate} - {sdate}";
                BindGrid();
            }
        }
        protected void btnBind_Click(object sender, EventArgs e)
        {

            // Get the date range from the hidden field
            string time = hdnDateRange.Value;
            string[] dates = time.Split('-');

            if (dates.Length == 2)
            {
                DateTime startDate, endDate;

                // Try parsing in the format "yyyy-MM-dd" first, then "dd MMM yyyy"
                string[] formats = { "yyyy-MM-dd", "dd MMM yyyy" };

                if (DateTime.TryParseExact(dates[0].Trim(), formats, null, System.Globalization.DateTimeStyles.None, out startDate) &&
                    DateTime.TryParseExact(dates[1].Trim(), formats, null, System.Globalization.DateTimeStyles.None, out endDate))
                {
                    // Format dates as "dd MMM yyyy"
                    fdate = startDate.ToString("dd MMM yyyy");
                    sdate = endDate.ToString("dd MMM yyyy");

                    // Update the span with the formatted date range
                    datevalspan.InnerText = $"{fdate} - {sdate}";

                    // Call any data binding method if needed
                    BindGrid();
                }
                else
                {
                    // Handle invalid date format (e.g., set default values or log an error)
                    fdate = DateTime.Today.AddMonths(-1).ToString("dd MMM yyyy");
                    sdate = DateTime.Today.ToString("dd MMM yyyy");
                    datevalspan.InnerText = $"{fdate} - {sdate}";

                }
            }
        }
        protected void btnexcel_Click(object s, ImageClickEventArgs e)
        {
            fdate = (Session["fromdate"] != null && Session["fromdate"].ToString() != "") ? Session["fromdate"].ToString() : "";
            sdate = (Session["Todate"] != null && Session["Todate"].ToString() != "") ? Session["Todate"].ToString() : "";

            ds = BindGrid();
            if (ds != null)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    string attachment = "attachment; filename=OrderBook_Offline_(" + DateTime.Now.ToString("ddMMMyyyy") + ").xls";
                    Response.ClearContent();
                    Response.AddHeader("content-disposition", attachment);
                    Response.ContentType = "application/vnd.ms-excel";
                    string tab = "";
                    foreach (DataColumn dc in ds.Tables[0].Columns)
                    {
                        Response.Write(tab + dc.ColumnName);
                        tab = "\t";
                    }
                    Response.Write("\n");
                    int i;
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        tab = "";
                        for (i = 0; i < ds.Tables[0].Columns.Count; i++)
                        {
                            Response.Write(tab + dr[i].ToString());
                            tab = "\t";
                        }
                        Response.Write("\n");
                    }
                    Response.End();
                }
                else
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('No Data !!!');", true);

            }
            else
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('No Data !!!');", true);


        }
        public DataSet BindGrid()
        {
            ScriptManager.RegisterStartupScript(this, GetType(), "ShowLoader", "showLoader();", true);
             string appno = txtAppNo.Text;
            string bidid = txtBidId.Text;
            string pan = txtPAN.Text;
            string cname = drpcompany.SelectedValue;
            string category = drpCategory.SelectedValue;
            string userid = drpUser.SelectedValue;
            DateTime startDate, endDate;
            if (DateTime.TryParseExact(fdate, "dd MMM yyyy", null, System.Globalization.DateTimeStyles.None, out startDate) &&
                 DateTime.TryParseExact(sdate, "dd MMM yyyy", null, System.Globalization.DateTimeStyles.None, out endDate))
            {
                fdate = startDate.ToString("yyyy-MM-dd");
                sdate = endDate.ToString("yyyy-MM-dd");
                Session["FromDate"] = fdate;
                Session["ToDate"] = sdate;
            }
            SqlParameter[] parameters = {
             new SqlParameter("@fdate", fdate),
             new SqlParameter("@sdate", sdate),
             new SqlParameter("@appno", appno),
          new SqlParameter("@pan", pan),
             new SqlParameter("@cname", cname),
             new SqlParameter("@category", category),
             new SqlParameter("@userid", userid),
              new SqlParameter("@Type", "OfflineReport") };
            ds = SqlHelper.ExecuteDataset(consString, CommandType.StoredProcedure, "OrderReport", parameters);
            ScriptManager.RegisterStartupScript(this, GetType(), "HideLoader", "hideLoader();", true);

            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                GridView1.DataSource = ds;
                GridView1.DataBind();
                nodatadivopen.Visible = false;
            }
            else
            {
                GridView1.DataSource = null;
                GridView1.DataBind();
                nodatadivopen.Visible = true;
            }
            return ds;
        }
        [WebMethod]
        public static List<ListItem> Getsymbol()
        {
            string query = "select distinct symbol from IPObidfiledetailsoffline";
            string constr = ConfigurationManager.ConnectionStrings["IPOOnline"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    List<ListItem> symbol = new List<ListItem>();
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            symbol.Add(new ListItem
                            {
                                Value = sdr["symbol"].ToString(),
                                Text = sdr["symbol"].ToString()
                            });
                        }
                    }
                    con.Close();
                    return symbol;
                }
            }
        }

        [WebMethod]
        public static List<ListItem> GetCategory()
        {
            string query = "select distinct Category from IPObidfiledetailsoffline";
            string constr = ConfigurationManager.ConnectionStrings["IPOOnline"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    List<ListItem> Category = new List<ListItem>();
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            Category.Add(new ListItem
                            {
                                Value = sdr["Category"].ToString(),
                                Text = sdr["Category"].ToString()
                            });
                        }
                    }
                    con.Close();
                    return Category;
                }
            }
        }

        [WebMethod]
        public static List<ListItem> GetApplicantName()
        {
            string query = "select distinct ApplicantName,uccId from IPObidfiledetailsoffline";
            string constr = ConfigurationManager.ConnectionStrings["IPOOnline"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    List<ListItem> ApplicantName = new List<ListItem>();
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            ApplicantName.Add(new ListItem
                            {
                                Value = sdr["uccId"].ToString(),
                                Text = sdr["ApplicantName"].ToString()
                            });
                        }
                    }
                    con.Close();
                    return ApplicantName;
                }
            }
        }
         

    }
}

Conclusion

This implementation demonstrates how to build a real-time, filterable GridView using AJAX WebMethod, dynamic dropdowns, and DatePicker filtering in classic ASP.NET Web Forms. It’s fast, efficient, and scalable for enterprise-level applications.