Pages

Search

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>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <style type="text/css">
        .Grid_Header_Cell
        {
            position: relative;
            background-color: White;
            border: 2px solid silver;
        }
        .Grid_Header
        {
            position: relative;
        }
    </style>
    <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";
            hdrtr.style.top = dv.scrollTop - 2;
            hdrtr.style.left = dv.scrollLeft - 1;
        }
    </script>
    <div style="height: 200px; overflow: auto" id="div_scr">
        <div>
            <asp:GridView ID="grd" runat="server" Width="98%">
            </asp:GridView>
        </div>
    </div>
</asp:Content>



Aspx.cs

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)
        {
            Bind();
            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));
        dt1.Columns.Add("col2");

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

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



No comments:

Post a Comment