Thursday, March 8, 2012

Freezing Header Row in Grid view

When we use asp:gridview to bind data, it is required to freeze the header row when there are more rows and also when grid is embedded in a div to show scroll bar when grid height falls outside the div height.

Below source (javascript) helps to make the header freezed.

Aspx Page

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <style type="text/css">
            position: relative;
            background-color: White;
            border: 2px solid silver;
            position: relative;
    <script type="text/javascript">
        function freezeGridHeader(grdid, divid) {
            var tbl = document.getElementById("MainContent_" + grdid);
            var dv = document.getElementById(divid);
            var hdrtr = tbl.getElementsByTagName("tr")[0];
            hdrtr.className = "Grid_Header";
            var hdrth = hdrtr.getElementsByTagName("th");
            for (i = 0; i < hdrth.length; i++)
                hdrth[i].className = "Grid_Header_Cell";
   = dv.scrollTop - 2;
   = dv.scrollLeft - 1;
    <div style="height: 200px; overflow: auto" id="div_scr">
            <asp:GridView ID="grd" runat="server" Width="98%">


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class _Default : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        if (!Page.IsPostBack)
            Page.ClientScript.RegisterStartupScript(typeof(_Default), "grid_header_freeze", "<script>setTimeout(\"freezeGridHeader('grd','div_scr');\",100);</script>");

    private void Bind()
        DataTable dt1 = new DataTable();
        dt1.Columns.Add("col1", typeof(System.Int32));

        DataRow dr = dt1.NewRow();
        dr["col1"] = 1;
        dr["col2"] = "Row1";

        for (int i = 2; i < 100; i++)
            dr = dt1.NewRow();
            dr["col1"] = i;
            dr["col2"] = "Row"+i;
        grd.DataSource = dt1;

No comments:

Post a Comment