Freeze asp.net grid view column

yadavr picture yadavr · Nov 23, 2012 · Viewed 54.3k times · Source

How can i freeze initial 2 -3 leftmost column in asp.net grid view? so that while horizontal scrolling initial 2 - 3 columns that got freezes will always be display.

Any answers??

Answer

StuartLC picture StuartLC · Nov 23, 2012

Yes, it seems to be possible with some css magic, with the pinned and scrollable columns on different z-indexes to keep the pinned on top. This comes with the caveat that overflow:scroll may not be 100% portable (I've tested on IE 8/9 and Chrome FWIW).

Take a look at this jsFiddle here

The ASPX I used to generate the GridView is below.

Note the css classes pinned and scrollable for fixed and scrolling columns respectively (applied to headers and items)

But the real work is done in the css. Note especially that you need to fiddle to get your column widths correct to align the fixed td's / th's at the left.

aspx

<div id="scrolledGridView">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="Col 1">
                <HeaderStyle CssClass="pinned col1"></HeaderStyle>
                <ItemStyle CssClass="pinned col1"></ItemStyle>
            </asp:BoundField>
            <asp:BoundField DataField="Name" HeaderText="Column 2">
                <HeaderStyle CssClass="pinned col2"></HeaderStyle>
                <ItemStyle CssClass="pinned col2"></ItemStyle>
            </asp:BoundField>
            <asp:BoundField DataField="Description" HeaderText="Column 3">
                <HeaderStyle CssClass="scrolled"></HeaderStyle>
                <ItemStyle CssClass="scrolled"></ItemStyle>
            </asp:BoundField>
            <asp:BoundField DataField="Cost" HeaderText="Column 4">
                <HeaderStyle CssClass="scrolled"></HeaderStyle>
                <ItemStyle CssClass="scrolled"></ItemStyle>
            </asp:BoundField>
        </Columns>
    </asp:GridView>

css

    #scrolledGridView
    {
        overflow-x: scroll; 
        text-align: left;
        width: 400px; /* i.e. too small for all the columns */
    }

    .pinned
    {
        position: fixed; /* i.e. not scrolled */
        background-color: White; /* prevent the scrolled columns showing through */
        z-index: 100; /* keep the pinned on top of the scrollables */
    }
    .scrolled
    {
        position: relative;
        left: 150px; /* i.e. col1 Width + col2 width */
        overflow: hidden;
        white-space: nowrap;
        min-width: 500px; /* set your real column widths here */
    }
    .col1
    {
        left: 0px;
        width: 50px;
    }
    .col2
    {
        left: 50px; /* i.e. col1 Width */
        width: 100px;
    }