Advertisements

Wednesday, December 4, 2013

// // 2 comments

GridView with Fixed Header & Scroll Bar

Hi,

In previous posts, I have completed two important topics of GridView.
  1. Paging in GridView
  2. Scroll Bars in GridView
Today, Lets learn another new and important trick with GridView, i.e. Fixed Headers. When we have to scroll through GridView, then there is must have feature that is Fixed Header. On recent post I have written about Fixed Headers in Excel, did you get chance to read them. We are doing exactly same task here. But here we do not have "Fix Pane" as in Excel anywhere. Lets do this with simple CSS and some enhance with code-behind.

Also, Today I am using Manual method of GridView creation, in previous demos and posts, I have used Drag & Dropped GridView control. Today here is manually coded GridView. 
Lets see code for ASPX page.
            <h2 align="center">GridView with Fixed Header</h2>
            <div style="height: 400px; overflow: auto" align="center">
                <asp:GridView ID="gvDistricts" runat="server" HeaderStyle-CssClass="FixedHeader" HeaderStyle-BackColor="YellowGreen" 
                    AutoGenerateColumns="false" AlternatingRowStyle-BackColor="WhiteSmoke" OnRowDataBound="gvDistricts_RowDataBound">
                    <Columns>
                        <asp:TemplateField HeaderText="District ID" HeaderStyle-Width="80px" ItemStyle-Width="80px">
                            <ItemTemplate>
                                <asp:Label ID="lblDistID" runat="server" Text='<%#Eval("DistID")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <Columns>
                        <asp:TemplateField HeaderText="District Name" HeaderStyle-Width="120px" ItemStyle-Width="120px">
                            <ItemTemplate>
                                <asp:Label ID="lblDistName" runat="server" Text='<%#Eval("DistName")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <Columns>
                        <asp:TemplateField HeaderText="Description" HeaderStyle-Width="200px" ItemStyle-Width="200px">
                            <ItemTemplate>
                                <asp:Label ID="lblDistDesc" runat="server" Text='<%#Eval("DistDesc")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </div>

In above design, Notable code is style for DIV which will make this GridView scrollable if its height exceeds than 400px. Another notable code is HeaderStyle-CssClass="FixedHeader". This line of code will apply a custom CSS Class named FixedHeader which we will create in while to do the task required. Before doing this lets bind this GridView with Data. Lets move to Back-end.
I am using data from a SQL table, which simply contains, DistrictID, DistName, DistDesc as its field and approx 25 records filled.

We have nothing to do more here. So simply write the databind code inside Page_Load Event.

protected void Page_Load(object sender, EventArgs e)
    {
        string ConStr = "Data Source=.\\sqldb;Initial Catalog=ShikshaNet;Integrated Security=True";
        if (!IsPostBack)
        {
            string Query = "SELECT * FROM Districts";
            SqlConnection con = new SqlConnection(ConStr);
            SqlDataAdapter adp = new SqlDataAdapter(Query, con);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            gvDistricts.DataSource = dt.DefaultView;
            gvDistricts.DataBind();
        }
    }
Now lets loot at browser to know how it looked.
 Perfect as designed. Lets scroll it and look for headers.

Oh! no, Headers are not visible. Lets start what we left at beginning. Add some style to GridView. Just navigate inside Head section of HTML and then add below code. This is stylesheet, you can customize as your requirement, but remember to change your Class name in GridView also if you are changing class name here.
<style type="text/css">
        .FixedHeader {
            position: absolute;
            font-weight: bold;
        }      
    </style>

OK, Lets refresh browser to see the changes.
 On scrolling,
Perfect, Headers are on top. But there is some problem. If you noticed, First record of GridView is not visible. It has dis-appeared. To make that record visible. Lets use a trick. Write some code in RowDataBound Event of GridView.

   protected void gvDistricts_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.RowIndex == 0)
                e.Row.Style.Add("height", "50px");
        }
    }
We just told Server to add some space if the RowIndex is 0 means first row of GridView should have atleast double space so that the value can be visible.
Lets see the output.

Bingo! You have created a perfect and complete GridView with Fixed Headers. You can use this code and it works fine even used with Paging across multiple browsers.

Thanks to +Amit Jain for the Top row fix which he has posted in his blog at Scrollable GridView With Fixed Headers Asp.Net.
If you found this post useful or helpful, or you have some suggestions to make, please post as comment or send me message on Google+ also.
+John Bhatt 


Tags: Gridview, ASP.NET, Tutorials by John Bhatt, P.Yar.B Complex, Fixed, Freeze, Headers, CSS, C-Sharp, Scrollbar, Tricks

2 comments:

  1. find this simple example of freeze and scroll.....Gridview freeze and scroll
    ling

    ReplyDelete
  2. HI

    Thanks for the article.I am trying to implement it however.

    I bind the gridview to a blank datatable so that the grid header always shows for some reason when adding your code the the grid header doesn't spread across the full webpage but once i bond it to actual data the underlying datarows do take on the correct widths. Any suggestions would be appreciated.

    Regards

    Meir

    ReplyDelete

Leave your Feedback or Suggestion. We will be Happy to read and reply.