ASP.NET Gridview Header column not freezing properly

BeUnique 2,232 Reputation points
2024-11-19T09:44:51.4+00:00

I'm using gridview with freezing header in ASP.NET application.

But, freezing is not showing while running the application.

what is the issue in the below code...?

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test_Pagination.aspx.cs" Inherits="Test_Pagination" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Test - Grid Freeze</title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/fixedcolumns/4.1.0/js/dataTables.fixedColumns.min.js"></script>
    <link href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
    <link href="https://cdn.datatables.net/fixedcolumns/4.1.0/css/fixedColumns.dataTables.min.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        .auto-style1 {
            width: 600px;
            border-style: solid;
            border-width: 2px;
        }
        .dataTables_scrollHead {
            width: 600px !important;
        }
        .dataTables_scrollHeadInner {
            width: 600px !important;
        }
        .dataTables_scrollBody {
            width: 600px !important;
        }
    </style>
    <script type="text/javascript">
        $(function () {
            $('#gvCustomer tfoot tr').appendTo('#gvCustomer thead');
            $('#gvCustomer').removeAttr('width').DataTable({
                bFilter: true,
                bSort: true,
                scrollY: "150px",
                scrollCollapse: true,
                paging: false,
                fixedColumns: false,
                orderCellsTop: true
            });
        });
    </script>
     <%-- //********* Script for myModel - Modal Popup  ******************//--%>
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
 <%--<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>--%>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 <script type='text/javascript'>
     function openModal() {
         $('[id*=PopModal]').modal('show');
     }
 </script>
 <%--  //********* Script for myModel  - Modal Popup  ******************//--%>
     <%-- //***** for search dropdown stylesheet and js files *************--%>
 <%--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />--%>
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/css/bootstrap-select.css" />
 <%--<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>--%>
 <%--<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>--%>
 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/js/bootstrap-select.js"></script>
 <script type="text/javascript">
     $(function () {
         $("[id*=drpEmployee]").selectpicker();
     });
     //On UpdatePanel Refresh
     var prm = Sys.WebForms.PageRequestManager.getInstance();
     if (prm != null) {
         prm.add_endRequest(function (sender, e) {
             if (sender._postBackSettings.panelsToUpdate != null) {
                 $("[id*=drpEmployee]").selectpicker();
             }
         });
     };
 </script>
  <script type="text/javascript">
      window.onload = function () {
          var grid = document.getElementById('<%= gvCustomer.ClientID %>');
          var tbody = grid.getElementsByTagName("tbody")[0]; //gets the first and only tbody
          var firstTr = tbody.getElementsByTagName("tr")[0]; //gets the first tr, hopefully contains the th's
          tbody.removeChild(firstTr); //remove tr's from table
          var newTh = document.createElement('thead'); //creates thead
          newTh.appendChild(firstTr); //puts ths in thead
          grid.insertBefore(newTh, tbody); //puts thead behore tbody
      }
  </script>
    <script type="text/javascript">
        function SelectAll(headerCheckBox) {
            //Get the reference of GridView.
            var GridView = document.getElementById("gvCustomer");
            //Loop through all GridView Rows except first row.
            for (var i = 1; i < GridView.rows.length; i++) {
                //Reference the CheckBox.
                var checkBox = GridView.rows[i].cells[0].getElementsByTagName("input")[0];
                checkBox.checked = headerCheckBox.checked;
            }
        }
    </script>
    <script type="text/javascript">
        function SelectOne(chk) {
            //Get the reference of GridView.
            var GridView = chk.parentNode.parentNode.parentNode.parentNode;
            //Reference the Header CheckBox.
            var headerCheckBox = GridView.rows[0].cells[0].getElementsByTagName("input")[0];;
            var checked = true;
            //Loop through all GridView Rows.
            for (var i = 1; i < GridView.rows.length; i++) {
                //Reference the CheckBox.
                var checkBox = GridView.rows[i].cells[0].getElementsByTagName("input")[0];
                if (!checkBox.checked) {
                    checked = false;
                    break;
                }
            }
            headerCheckBox.checked = checked;
        };
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div class="modal fade" id="PopModal" role="dialog">
            <div class="modal-dialog">
                <!-- Modal content-->
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">
                            &times;</button>
                        <h4 class="modal-title">Invoice Details</h4>
                    </div>
                    <div class="modal-body">
                        <div class="col-lg-12 col-sm-12 col-md-12 col-xs-12">
                            <div class="form-group">
                                <asp:Label ID="Label1" runat="server" CssClass="tdLabel" Text="File Name :"></asp:Label>
                                <asp:Label ID="lblFileName" CssClass="tdLabel" runat="server" Text="Label"></asp:Label>
                            </div>
                            <div class="form-group">
                                <asp:Label ID="lblid" runat="server" Text=""></asp:Label>
                            </div>
                            <div class="form-group">
                                <iframe id="iframe" runat="server" width="500" height="500"></iframe>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <asp:ScriptManager ID="ScrMgr2" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel runat="server" ID="UpdatePanel1">
            <ContentTemplate>
                <table style="font-family: 'Blender Pro'; font-weight: bold; font-size: 16px; width: 100%; color: #22505F;">
                    <tr>
                        <td>
                            <asp:Label ID="lblDispName" runat="server" Text="Employee Name :"></asp:Label>
                            <asp:DropDownList ID="drpEmployee" runat="server"
                                AutoPostBack="true" class="selectpicker" data-live-search="true">
                            </asp:DropDownList>
                        </td>
                        <td align="left" style="width: 40%">
                            <asp:Button ID="btnSearch" runat="server" CssClass="btnGenerate" Text="SEARCH" OnClick="btnSearch_Click" />
                            &nbsp;&nbsp;&nbsp;&nbsp;
                            <asp:Button ID="btnClear" runat="server" CssClass="btnGenerate" Text="CLEAR" OnClick="btnClear_Click" />
                        </td>
                    </tr>
                </table>
            </ContentTemplate>
        </asp:UpdatePanel>
        <div id="dvGrid" style="width: 100%">
            <asp:UpdatePanel runat="server" ID="UpdatePanel2">
                <ContentTemplate>
                    <asp:GridView ID="gvCustomer" Width="100%" AutoGenerateColumns="False" runat="server"
                        Font-Size="12px"
                        DataKeyNames="Id">
                        <AlternatingRowStyle BackColor="white" />
                        <Columns>
                            <asp:TemplateField>
                                <HeaderTemplate>
                                    <asp:CheckBox ID="chkAll" runat="server" onclick="SelectAll(this)" />
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <asp:CheckBox ID="chk" runat="server" onclick="SelectOne(this)" />
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="ID">
                                <ItemTemplate>
                                    <asp:Label ID="Id" runat="server" Text='<%# Eval("Id") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField>
                                <HeaderTemplate>
                                    <label style="text-align: center; display: block;">Sl No.</label>
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <%# Container.DataItemIndex + 1 %>
                                </ItemTemplate>
                                <ItemStyle HorizontalAlign="Center" />
                            </asp:TemplateField>
                            <asp:TemplateField ItemStyle-HorizontalAlign="left">
                                <HeaderTemplate>
                                    <label style="text-align: center; display: block;">Emp No.</label>
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblCustNo" Style="text-align: left; line-height: 28px;"
                                        runat="server" Text='<%# Eval("EmpId")%>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                              <asp:TemplateField ItemStyle-HorizontalAlign="left">
                        <HeaderTemplate>
                            <label style="text-align: center; display: block;">Emp Name.</label>
                        </HeaderTemplate>
                        <ItemTemplate>
                            <asp:Label ID="lblCustName" Style="line-height: 28px;"
                                runat="server" Text='<%# Eval("EmpName")%>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                            <asp:TemplateField ItemStyle-HorizontalAlign="Center">
                                <HeaderTemplate>
                                    <label style="text-align: center; display: block;">
                                        View File
                                    </label>
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <asp:LinkButton ID="lnkBtnView" runat="server" Text="View"
                                        OnClick="Display"></asp:LinkButton>
                                    <asp:HiddenField ID="HiddenField1" runat="server"
                                        Value='<%# Eval("FilePath")%>' />
                                    <asp:HiddenField ID="HdnFileName" runat="server"
                                        Value='<%# Eval("FileName")%>' />
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                        <HeaderStyle BackColor="#2F6370" Font-Names="Arial" Font-Size="12px" ForeColor="White" />
                        <SelectedRowStyle BackColor="#007D8C" Font-Bold="True" ForeColor="White" />
                    </asp:GridView>
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>

ASPX.CS
* *******
using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.IO;
namespace Test
{
    public partial class Test_Pagination : System.Web.UI.Page
    {
        private string str = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
        string sRoot = @"\\net.venem.intranet\srv1\Team10\IT\AccFiles\";
        DataTable rstData = new DataTable();
        private DataSet ds = new DataSet();
        public string EmpNo = string.Empty;
        public string EmpName = string.Empty;
        private string filename = string.Empty;
        private string FileType = String.Empty;
        //private DateTime dtBillDate;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    //****** To get emp name and assign to label
                    //lblFileUploadName.Text = "";
                    if (HttpContext.Current.Session["Empno"] == null)
                    {
                        Response.Redirect("SessionExpired.aspx");
                    }
                    else
                    {
                        EmpName = HttpContext.Current.Session["EmpName"].ToString();
                        EmpNo = HttpContext.Current.Session["Empno"].ToString();
                        //lblEmpName.Text = string.Concat(EmpName, StrHyphen, EmpNo);
                    }
                    GetEmpDetails();
                    GetEmpAccDetails();
                    Session["rstData"] = rstData;
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    // ds = Nothing
                    // ds.Dispose()
                }
            }
            else
            {
                rstData = Session["rstData"] as DataTable;
            }
            foreach (var item in gvCustomer.Rows)
            {
                LinkButton btnDisplay = (LinkButton)((GridViewRow)item).FindControl("lnkBtnView");
                // Get current ScriptManager on the page
                ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(btnDisplay);
                if (!string.IsNullOrEmpty(btnDisplay.CommandArgument))
                {
                    ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(btnDisplay);
                }
            }
        }
        private void GetEmpDetails()
        {
            try
            {
                dbConn.sqlCmd.Parameters.Clear();
                dbConn.sqlCmd.Parameters.AddWithValue("@Spd_TYPE", "GET_EmpList");
                ds = dbConn.XcuteResult(str, CommandType.StoredProcedure, "Spd_EmpDetails_Master");
                drpEmployee.DataSource = ds.Tables[0].DefaultView;
                drpEmployee.DataTextField = ds.Tables[0].Columns[0].ColumnName;
                drpEmployee.DataValueField = ds.Tables[0].Columns[0].ColumnName;
                drpEmployee.DataBind();
            }
            catch (Exception ex)
            {
            }
            finally
            {
                ds = null;
            }
        }
        private void GetEmpAccDetails()
        {
            try
            {
                dbConn.sqlCmd.Parameters.Clear();
                dbConn.sqlCmd.Parameters.AddWithValue("@Spd_Type", "GetEmpAccDetails");
                //dbConn.sqlCmd.Parameters.AddWithValue("@Spd_Flag", Flag.ToString().Trim());
                ds = dbConn.XcuteResult(str, CommandType.StoredProcedure, "Spd_EmpDetails_Master");
                if ((ds.Tables[0].Rows.Count > 0))
                {
                    //gvBills.Visible = true;
                    rstData = ds.Tables[0];
                    gvCustomer.DataSource = rstData;
                    gvCustomer.DataBind();
                    //lblNoRecord.Visible = false;
                }
                else
                {
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                ds = null;
            }
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string ddlEmpvalue = string.Empty;
            if (drpEmployee.SelectedValue == "")
            {
                ddlEmpvalue = "";
            }
            else
            {
                ddlEmpvalue = drpEmployee.SelectedValue;
            }
            try
            {
                dbConn.sqlCmd.Parameters.Clear();
                dbConn.sqlCmd.Parameters.AddWithValue("@Spd_TYPE", "Search_EmpDetails");
                dbConn.sqlCmd.Parameters.AddWithValue("@Spd_EmpNo", ddlEmpvalue.ToString().Trim()); //Employee value
                ds = dbConn.XcuteResult(str, CommandType.StoredProcedure, "Spd_EmpDetails_Master");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    gvCustomer.DataSource = ds.Tables[0];
                    gvCustomer.DataBind();
                }
                else
                {
                    ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                    gvCustomer.DataSource = ds.Tables[0];
                    gvCustomer.DataBind();
                    int TotalColumns = gvCustomer.Rows[0].Cells.Count;
                    gvCustomer.Rows[0].Cells.Clear();
                    //gvCustomer.Rows[0].Cells.Add(new TableCell());
                    gvCustomer.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                    gvCustomer.Rows[0].Cells[0].Text = "No record(s) Found";
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                ds = null;
            }
        }
        protected void btnClear_Click(object sender, EventArgs e)
        {
            drpEmployee.SelectedIndex = -1;
            GetEmpAccDetails();
        }
        protected void Display(object sender, EventArgs e)
        {
            Session["FPath"] = null;
            int rowIndex = Convert.ToInt32(((sender as LinkButton).NamingContainer as GridViewRow).RowIndex);
            GridViewRow row = gvCustomer.Rows[rowIndex];
            string FPath = (row.FindControl("HiddenField1") as HiddenField).Value;
            Session["FPath"] = FPath;
            HiddenField HiddenField1 = (row.FindControl("HiddenField1") as HiddenField);
            string FileName = (row.FindControl("HdnFileName") as HiddenField).Value;
            string sMineType = MimeMapping.GetMimeMapping(FPath);
            if (!string.IsNullOrEmpty(FPath))
            {
                if (File.Exists(FPath))
                {
                    lblFileName.Text = FileName.ToString();
                    byte[] rawFile = File.ReadAllBytes(FPath);
                    iframe.Attributes["src"] = $@"data:{sMineType};base64,{Convert.ToBase64String(rawFile)}";
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "No Data", "alert(\'File is missing in the folder..!.\');", true);
                }
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "No Data", "alert(\'No data found..!.\');", true);
            }
            HiddenField1.Visible = false; //Hide the path
        }
    }
}

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,542 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,125 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jalpa Panchal-MSFT 705 Reputation points Microsoft Vendor
    2024-11-19T13:59:19.2833333+00:00

    Hi @BeUnique ,

    You could try this below code to freeze the header

    WebForm1.aspx:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>GridView Header Freeze</title>
        <style>
            /* Style the GridView container for scrolling */
            .grid-container {
                height: 300px;
                overflow-y: auto;
                border: 1px solid #ddd;
            }
    /* Ensure the header is sticky */
            .grid-view-header th {
                position: sticky;
                top: 0;
                background-color: #2F6370;
                color: white;
                z-index: 10;
                padding: 10px;
            }
    .grid-view-row td {
                padding: 10px;
            }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
            <div class="grid-container">
                <asp:GridView ID="gvCustomer" runat="server" AutoGenerateColumns="False" CssClass="grid-view">
                    <HeaderStyle CssClass="grid-view-header" />
                    <RowStyle CssClass="grid-view-row" />
                    <Columns>
                        <asp:TemplateField>
                            <HeaderTemplate>
                                <asp:CheckBox ID="chkAll" runat="server" onclick="SelectAll(this)" />
                            </HeaderTemplate>
                            <ItemTemplate>
                                <asp:CheckBox ID="chk" runat="server" onclick="SelectOne(this)" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:BoundField DataField="Id" HeaderText="ID" />
                        <asp:BoundField DataField="EmpId" HeaderText="Emp No." />
                        <asp:BoundField DataField="EmpName" HeaderText="Emp Name" />
                    </Columns>
                </asp:GridView>
            </div>
        </form>
    </body>
    </html>
    

    WebForm1.aspx.cs:

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    namespace WebApplication2
    {
        public partial class WebForm1 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindGrid();
                }
            }
            private void BindGrid()
            {
                // Sample Data
                DataTable dt = new DataTable();
                dt.Columns.Add("Id");
                dt.Columns.Add("EmpId");
                dt.Columns.Add("EmpName");
                for (int i = 1; i <= 20; i++)
                {
                    dt.Rows.Add(i, "EMP" + i.ToString("D3"), "Employee " + i);
                }
                gvCustomer.DataSource = dt;
                gvCustomer.DataBind();
            }
        }
    }
    

    User's image

    Best Regards,

    Jalpa


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.