Freezing Gridview Header with Dynamic Column Orders: A Step-by-Step Guide

My Gridview in ASPX Page with Dynamically Generated Column Names:

<div id="header" style="height: 200px;overflow:scroll ">
     <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" >
     <HeaderStyle CssClass="fixedHeader" />
     </asp:GridView>
     </div>
    

CSS Class Used to Freeze Header :

    .fixedHeader
        {
            background-color:Gray;
            position: relative;
            cursor: default;            
            top: expression(document.getElementById("header").scrollTop-2); 
            z-index: 10;
    
        }
    

I have tried implementing this using JavaScript and jQuery but it's not working. I have looked at examples from various sources like Asspsnippet, Codeproject, etc. Can someone please assist me? Thank you.

Answer №1

Method 1:

  1. To set the GridView with thead as header and tbody as body, utilize RowDataBound to assign GridView.HeaderRow.TableSection = TableRowSection.TableHeader;
  2. Implement the concept found here: http://css-tricks.com/snippets/jquery/persistant-headers-on-tables/
  3. Adjust the code slightly to wait for image loading before adjusting th element widths:

    window.onload = function () { $("table.tableWithFloatingHeader").each(function () { $(this).wrap("");

        $("tr:first", this).before($("tr:first", this).clone());
        clonedHeaderRow = $("tr:first", this);
        clonedHeaderRow.addClass("tableFloatingHeader");
        clonedHeaderRow.css("position", "absolute");
        clonedHeaderRow.css("top", "0px");
        clonedHeaderRow.css("left", "0px");
        clonedHeaderRow.css("visibility", "hidden");
    
        var row_ths = $("tr:nth-child(2)", this).children("th");
        var crow_ths = $("tr:nth-child(1)", this).children("th"); ;
    
        for (var i = 0; i < row_ths.size(); ++i) {
            crow_ths.eq(i).width(row_ths.eq(i).width() + 2);
        }
    });
    

This method is compatible with IE8, Firefox, and Chrome.

Method 2:

For achieving this feature, JQuery and a bit of JavaScript are required. This allows the Gridview Data to be scrollable while keeping the header frozen on top. It proves beneficial when dealing with large amounts of data and needing to easily match columns with headings.

SOURCE

Answer №2

Here is a complete solution based on Solution 1 (Works Great, Looks Great).

Make sure to add the following code to your aspx file.

 <style>
    .floatingHeader {
      position: fixed;
      top: 0;
      visibility: hidden;
      background-color:antiquewhite;
       z-index: 1000;
    }
    </style>

<script>

function UpdateTableHeaders() {
    $(".persist-area").each(function () {

        var element         = $(this),
            offset          = element.offset(),
            scrollTop       = $(window).scrollTop(),
            floatingHeader  = $(".floatingHeader", this)

        if ((scrollTop > offset.top) && (scrollTop < offset.top + element.height())) {
            floatingHeader.css({
                "visibility": "visible"
            });
        } else {
            floatingHeader.css({
                "visibility": "hidden"
            });
        };
    });
}

$(document).ready(function() {

    $(window)
     .scroll(UpdateTableHeaders)
     .trigger("scroll");

});

window.onload = function () {
    $("table.tableWithFloatingHeader").each(function () {
        $(this).wrap("<div class='divTableWithFloatingHeader' style='position:relative'></div>");

        $("tr:first", this).before($("tr:first", this).clone());
        clonedHeaderRow = $("tr:first", this);
        clonedHeaderRow.addClass("floatingHeader");


        var rowThs = $("tr:nth-child(2)", this).children("th");
        var crowThs = $("tr:nth-child(1)", this).children("th"); ;

        for (var i = 0; i < rowThs.size(); ++i) {
            crowThs.eq(i).width(rowThs.eq(i).width() );
        }
    });
}
window.onresize = function () {
    $("table.tableWithFloatingHeader").each(function () {

        clonedHeaderRow = $("tr:first", this);

        var rowThs = $("tr:nth-child(2)", this).children("th");
        var crowThs = $("tr:nth-child(1)", this).children("th");;

        for (var i = 0; i < rowThs.size() ; ++i) {
            crowThs.eq(i).width(rowThs.eq(i).width());
        }
    });

}
</script>

Now, make sure to add the classes persist-area and tableWithFloatingHeader with HeaderStyle Class of persist-header to your table.

 <asp:GridView EnableViewState="false"  ID="grid_Results" runat="server" AutoGenerateColumns="False" Class="persist-area tableWithFloatingHeader">

Follow these steps and it should work perfectly.

If you also want to change the color of the header, follow these additional two steps.

Add the following CSS right after the style tag.

In the code-behind file (aspx.vb), add the following code to the DataBound event of the grid:

   Protected Sub grid_Results_DataBound(sender As Object, e As EventArgs) Handles grid_Results.DataBound
        If grid_Results.HeaderRow IsNot Nothing Then
            grid_Results.HeaderRow.TableSection = TableRowSection.TableHeader
        End If
    End Sub

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

Tips for formatting dt and dd elements side by side on one line

How can I use CSS to style the following content in two columns: <dl> <dt>Mercury</dt> <dd>Mercury (0.4 AU from the Sun) is the closest planet to the Sun and the smallest planet.</dd> <dt>Venus</dt> ...

Overriding the width value of a computed CSS style with an inline CSS style is not possible

There's a peculiar issue that has me stumped. The webpage I'm currently working on is loaded with CSS styles. To customize the width of one of my div elements, I added inline CSS code specifying the exact width I want (and it looks correct in th ...

What is the method for enumerating a single item?

Possible Duplicates: Creating a singleton IEnumerable instance? Best approach to generate a new IEnumerable<T> sequence from one value? If I want to return an IEnumerable with just one element... I could use a list like this: return new Li ...

Searching for grid rows that are missing corresponding entries in a separate table

My Telerik RadGrid is linked to a data source with the following Select query: SELECT g.GroupID, c.ClientName, r.CarrierName, p.PlanName FROM Group AS g JOIN Client AS c ON g.ClientID=c.ClientID JOIN Carrier AS r ON g.Ca ...

Parallel with one <div> and subsequently another <div>

I have been challenged by HTML and CSS to embrace humility: Attempting to replicate the following design: Here is my effort: <div> <div style="width:800px;"> <div style="float:left;width:25%;background-color:red;">Facility #: COM ...

Is there a way to utilize an Angular Material checkbox without any extra gaps or spacing?

Currently, I am working with Angular Material and trying to figure out how to remove the default spacing around the checkbox. The checkboxes in Angular Material are typically surrounded by some space (as shown in the image). Is there a simple way to elimin ...

Incorporating Visual Studio Commands (Buttons) into designated areas

Struggling to create my own Microsoft Visual Studio 2022 Extension (Community VSIX Project). After hours of searching and testing, I can't seem to figure out how to add my custom menu item to the Tools menu alongside Android, iOS, and Archive Manager ...

The Operator cannot be used with 'bool' and 'DayOfWeek' data types

On my website, there are checkboxes labeled Monday through Friday, allowing users to select any combination of days from this list. The CDay list represents the days of the week - Monday through Friday. My goal is to determine whether the user has selecte ...

Is it possible for a fixed SqlDBConnection to result in one thread accessing another thread's result set?

During the process of troubleshooting an issue with an ASP.NET project, a colleague pointed out an instance where a method was creating a static SqlConnection. If multiple threads are concurrently utilizing the same SqlConnection, is there a chance that o ...

What is the method to tap into the existing FormsAuthenticationModule in a Medium Trust setting?

Within my application, there is an HttpModule that connects to the FormsAuthenticationModule's Authenticate event using the code below: public void Init(HttpApplication context) { FormsAuthenticationModule faModule = (FormsAuthenticationM ...

The entered text did not adhere to the rightful format

Within my gridview, I have a footer template containing an insert link button, TextBox, and DropDownList. The gridview also includes options for editing, updating, and deleting, while the footer template contains dropdown lists with values from other table ...

Guide for selecting the appropriate .NET framework version in the ASP.NET tab within IIS for a web application

I am currently learning how to develop web applications in ASP.net. My project involves creating a simple web service calculator that adds two numbers together. However, when I try to invoke the calculator, I encounter an error: The resource cannot be fou ...

Is there a way to apply border-radius to an element with a scrollbar?

https://i.sstatic.net/aJsL8.png I attempted the following approach: element::-webkit-scrollbar-corner { border-bottom-right-radius: 20px !important; } however, it did not yield the desired result. ...

Problem with CSS inline-block bottom margins

How can I resolve the issue with inline-block in CSS causing a 1px whitespace? Changing word-spacing or letter-spacing does not solve the margin-bottom problem. Here are snippets from my HTML files: <!DOCTYPE html> <html lang="en> <head> ...

I'm attempting to incorporate the CSS file into the main HTML template, but the styling isn't being applied. My goal is to define the styles externally

The CSS style isn't being properly imported. Below is the base HTML file (base.html) I'm using: <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <meta name="viewport" content="widt ...

Issue with setting cookie in ASP.NET MVC IExceptionFilter

I've created a customized IExceptionFilter to address an issue that some users are encountering with a third-party library our application utilizes. The problem arises when a specific error occurs, and I need to update the user's cookies to reset ...

What is the best way to target the label of an unchecked radio button only if there is a single radio button checked?

Consider this HTML structure: <div> <input type="radio" id="a" name="a"><label for="a">aaaa</label> <input type="radio" id="b" name="a"><label for=&q ...

The HTML divider border is failing to encompass all of the subcontents

Giving HTML/CSS Django website creation a shot for the first time, appreciate your patience. I'm using a basic resume template and trying to troubleshoot an issue right from the beginning (template in question here). In one section of my website, the ...

Tips for avoiding cursor sticking in css rotate transform in firefox?

I have a unique challenge in this code where I want the user to grab the black square and rotate it around the inner circle. Check out the code snippet here. While attempting to rotate the square, you might notice that the cursor sometimes gets stuck in ...

Formatting specific elements within an input field text

Currently, I am developing a Web-GUI for a semantic search which involves using a single text-input as a search-box. The typical queries include phrases like "buildings higher than 100 meters". My goal is to enhance the user experience by formatting the i ...