Maintaining the gridview header position during scrolling

When I fixed the header of my GridView and scrolled down, the headers remained constant but were not displayed properly. All the column headers appeared shrinked and did not align with the respective columns. Despite trying various solutions, nothing seemed to work. In simple terms, the width of the headers did not match the columns. I utilized JavaScript for scrolling and applied a CssClass for fixing.

If you have a solution, please help me out.

JavaScript Code

<script type = "text/javascript">
        var GridId = "<%=GridViewLeaveHistory.ClientID %>";
        var ScrollHeight = 300;
        var ScrollWidth = 300;
        window.onload = function () {
            var grid = document.getElementById(GridId);
            var gridWidth = grid.offsetWidth;
            var gridHeight = grid.offsetHeight;
            var headerCellWidths = new Array();
            for (var i = 0; i < grid.getElementsByTagName("TH").length; i++) {
                headerCellWidths[i] = grid.getElementsByTagName("TH")[i].offsetWidth;
            }
            grid.parentNode.appendChild(document.createElement("div"));
            var parentDiv = grid.parentNode;

            var table = document.createElement("table");
            for (i = 0; i < grid.attributes.length; i++) {
                if (grid.attributes[i].specified && grid.attributes[i].name != "id") {
                    table.setAttribute(grid.attributes[i].name, grid.attributes[i].value);
                }
            }
            table.style.cssText = grid.style.cssText;
            table.style.width = gridWidth + "px";
            table.appendChild(document.createElement("tbody"));
            table.getElementsByTagName("tbody")[0].appendChild(grid.getElementsByTagName("TR")[0]);
            var cells = table.getElementsByTagName("TH");

            var gridRow = grid.getElementsByTagName("TR")[0];
            for (var i = 0; i < cells.length; i++) {
                var width;
                if (headerCellWidths[i] > gridRow.getElementsByTagName("TD")[i].offsetWidth) {
                    width = headerCellWidths[i];
                }
                else {
                    width = gridRow.getElementsByTagName("TD")[i].offsetWidth;
                }
                cells[i].style.width = parseInt(width - 3) + "px";
                gridRow.getElementsByTagName("TD")[i].style.width = parseInt(width - 3) + "px";
            }
            parentDiv.removeChild(grid);

            var dummyHeader = document.createElement("div");
            dummyHeader.appendChild(table);
            parentDiv.appendChild(dummyHeader);
            var scrollableDiv = document.createElement("div");
            if (parseInt(gridHeight) > ScrollHeight) {
                gridWidth = parseInt(gridWidth) + 17;
            }
            scrollableDiv.style.cssText = "overflow:auto;height:" + ScrollHeight + "px;width:" + gridWidth + "px" + ScrollWidth;
            scrollableDiv.appendChild(grid);
            parentDiv.appendChild(scrollableDiv);
        }

Css Class

.Freezing 
    { 
    position: relative;  
    top: expression(this.offsetParent.scrollTop-1); 
    z-index: 10; 
    }

GridView Code

<div style="width: 810px; height: 259px;">
 <asp:GridView ID="GridViewLeaveHistory" runat="server" AllowSorting="True" 
  AutoGenerateColumns="False" BackColor="White" BorderColor="#0061C1" 
  BorderStyle="None" CaptionAlign="Bottom" EmptyDataText="No Records Found" 
  Font-Names="Verdana" Font-Size="X-Small" ForeColor="#0061C1" Height="18px" 
  OnRowCommand="GridViewLeaveHistory_RowCommand" 
  OnRowDataBound="GridViewLeaveHistory_RowDataBound" CssClass="Freezing"                                                       
  OnSelectedIndexChanged="GridViewLeaveHistory_SelectedIndexChanged"                                                      
  ShowFooter="True" ShowHeaderWhenEmpty="True" width="801px">

Answer №1

Seems like a bit of overkill for such a simple header fix. Why not just adjust some classes on the element instead? Unless I'm misunderstanding your question...

<style>
// Add position: relative to the parent element you want to fix the header to
.table-responsive {
  position: relative;
  padding: 20px; // Consider adding some padding to prevent overlap with the first row
}

// Apply this class when you want the header to be fixed
// Change 'absolute' to 'fixed' if you want it fixed at the top of the document
.table-header {
  position: absolute;
  top: 0;
  left: 0;
}
</style>

Answer №2

    <!-- Customized Grid Header Script-->
    <script type="text/javascript">
        $(document).ready(function () {
            var gridHeader = $('#<%=GrdMWRFinal.ClientID%>').clone(true); // Create a copy of the Gridview with styling
            $(gridHeader).find("tr:gt(0)").remove(); // Remove all rows except for the first row (header row)
            $('#<%=GrdMWRFinal.ClientID%> tr th').each(function (i) {
                // Set the width of each header column in the new table to match the original gridview
                $("th:nth-child(" + (i + 1) + ")", gridHeader).css('width', ($(this).width()).toString() + "px");
            });
            $("#GHead1").append(gridHeader);
            $('#GHead1').css('position', 'top');
            $('#GHead1').css('top', $('#<%=GrdMWRFinal.ClientID%>').offset().top);
    
        });
    </script>
    <!-- Customized Grid Header Script-->


  <div id="divGridViewScroll1" style="height: 500px; overflow: scroll">
                                                                    <div class="table-responsive">

                                                                        <asp:GridView ID="grdEmpValidations" runat="server" CssClass="table table-small-font table-bordered table-striped">
                                                                            <Columns>
 </Columns>
                                                                            <HeaderStyle HorizontalAlign="Justify" VerticalAlign="Top"
                                                                                Font-Bold="true" />
                                                                            <RowStyle Font-Size="Small" Height="1" ForeColor="#000000" />
                                                                        </asp:GridView>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modifying characters within a designated class definition

I'm working on integrating Isotope with a CuteNews system, and in order to make the filtering function properly, I need to include some identifiers in my class declaration for each isotope item. Link to Isotope In CuteNews, my news items can have mul ...

Display a pop-up alert message when the session expires without the need to manually refresh the page

I have a query regarding the automatic display of an alert message. Even though I have set the time limit to 10 seconds, I still need to manually refresh the page for the alert message to appear. The alert message should notify the user that the session ...

The translateX property will be set to the offsetX value of the event when the mouse is moved, resulting in a

Here's a quick and easy question regarding some kind of scrubber tool. Check out the fiddle below. When using jQuery to bind to the mousemove event and adjusting the transformX property in the positive direction, there's a 50% chance it will ret ...

I am looking to dynamically load a script only after retrieving specific data from a JSON file in Next.js

I am trying to ensure that the Script tag loads after the data.post.content is loaded within the HTML. Specifically, my goal is to execute the MathJax.js script inside the HTML. This is the code I have: return ( <div> <h1>{data.post ...

Position the checkbox to the left of the label

I currently have a checkbox with ripple effects. The label text is displayed before the checkbox in the code. However, I'd like to change the order so that the checkbox comes before the label text. Occasionally, the entire div expands and contracts. ...

What is the method used by Chrome dev tools to create CSS selectors?

When setting a new style rule for an element, Chrome generates a selector that includes the entire hierarchy of elements instead of just the class name. For instance: <body> <div class="container"> <span class="helper"> ...

Instructions for including buttons and text boxes within an email body using C#

Currently, I am sending a string text as the email body. However, I would like to send an Ok and Cancel button along with some additional text. If the user clicks on Ok, a specific functionality should be executed. If they click on Cancel, a textbox shou ...

Is there a way to prevent the URL of my Next.js app from constantly changing?

Our current Next.js project requires that the static URL remains constant, even when navigating between pages. This is a client requirement that we must adhere to. Can you provide suggestions on how we can achieve this? Maintaining the same URL throughout ...

What could be causing my table to malfunction in IE8?

Is it just me, or do my CSS tables not work on IE8? <div class="main-table"> <div class="row"> <a class="secondary-table" href="#"> <div class="secondary-row"> <div class="secondary-cell"> ...

Adjusting the width of titles in a CSS menu upon hover

I am currently creating a basic CSS menu. However, I am facing an issue where selecting a menu title in the menu bar causes the width of the title to extend to match the width of the associated menu, which is not my desired outcome (the title's width ...

Webix UI - Struggling to create dynamically responsive components during screen resizing

Can anyone guide me on how to make my Webix UI control responsive in the free version available at ? It seems to be acting unpredictably due to the AngularJS integration code I'm using. I have attempted various solutions like media queries, redraw, a ...

Understanding the significance of underscores in JavaScript strings

Some places mention using _() around strings like _('some string'). For instance, in a desktop program with these imports: const Applet = imports.ui.applet; const St = imports.gi.St; const Gdk = imports.gi.Gdk; const Gtk = imports.gi.Gtk; const ...

Exploring ways to access global window variables in React using JavaScript

I've been following the discussion on how to transfer variables from JavaScript to ReactJS. Here is my array of objects in JavaScript: window.dataArr = []; function makeJsObj(descr, currDate, done) { var data = {}; console.log(descr ...

IE z-index anomaly

My line of floated divs reveals a popup when hovered over, but the popup appears under the following divs instead of on top. I've tried using z-index with no success to fix this issue. UPDATE: The problem has been resolved with some assistance, but i ...

How to target the following sibling element (not a child) with CSS

I am working with the following HTML structure: <div class="col-sm-12"> <input id="my_id"> <div class="col-sm-1 col-3-box" style="position:absolute; margin-left:340px;"> </div> </div> How can I target and change ...

Retrieve mongodb objects that fall within a specified date range

Within my collection, there is an example document structured as follows: { "_id" : ObjectId("5bbb299f06229dddbaab553b"), "phone" : "+38 (031) 231-23-21", "date_call" : "2018-10-08", "adress_delivery" : "1", "quantity_concrete" : "1", ...

Ensuring that the CSS aligns correctly with the HTML structure is essential in order to enable the hover

I am looking to have an image appear when a mouse hovers over ONLY the "name" of the food item, and not the "price" which is part of div.child. <div class="menu-block"> <div class ="menu-titles"><span><p class="title">Brunch< ...

Having trouble retrieving data from fetch operation

Having trouble with pulling and displaying search results on the Left page using the SearchFilms component? The API key has been deliberately removed, making it difficult for beginners to figure out what to do. Where should we start? import React, {Fragm ...

How come the button doesn't get enabled after three seconds even though ng-disabled is being used?

index.html <html ng-app='myApp'> <head> <title>TODO supply a title</title> <script src="js/angular.js" type="text/javascript"></script> <script src="js/using built-in directives. ...

The full background width is not being displayed as 100% on the

Unexpectedly, the "full left secondary-bg" background division on this particular page (http://goo.gl/OU4MkW) is no longer spanning the full width of the screen and I am unable to figure out why. This website is WordPress-based and constructed using the sk ...