Click here to Skip to main content
Click here to Skip to main content
Go to top

GridView with Fixed Header and Scroll Bar

, 18 Jan 2014
Rate this:
Please Sign up or sign in to vote.
Let's learn how to make a scrollable GridView and Fix headers with simple steps.

Introduction

GridView is one of the most used data bound controls in Visual Studio by any developer if the web application is interacting with database. Sometimes, we need to display a large amount of data in a GridView and that too in a small space or portion of web form. We will make a scrollable GridView here. And later, we will add a must have feature, i.e., Fixed Headers in GridView. Even we scroll GridView, headers will remain at the top and visible always.

Requirement

Technical Requirements:

  • Visual Web Developer or Visual Studio or similar tool.
  • A data source, SQL Server, XML file or other source. We will work here with SQL Server Database.
  • Some C# or VB for binding data to GridView and also writing some simple code. I am using C# here. Convert your code to VB from online tools if you are using Visual Basic.
  • Basic understanding of HTML.
  • Basic understanding of CSS.

Create a GridView

We will create a GridView, instead of using Drag and Drop concept, we will manually write code to generate GridView. Directly code for GridView in ASPX page.

  <asp:GridView ID="gvDistricts" 
runat="server" 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>  

Notable Points in the above code:

  • AutoGenerateColumns = "false": This will not generate columns itself according to data source columns.
  • HeaderStyle-Width="80px" ItemStyle-Width="80px": We have set the Value for width of Header and Item exactly same. If we do not apply this explicitly here, the Header will not appear properly while applied Fixed Header style.
  • Other is simple GridView code, having 3 Columns, getting value from Backend using Eval() method.

Bind Data

Now the next step is to Bind Data to GridView. Let's move to back-end and write some code to perform Data-binding. We have nothing more to do here, so I am going to write code inside Page_Load event.

protected void Page_Load(object sender, EventArgs e)
{
       string ConStr = "Data Source=localhost;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();
			}
	}   

This code will simply get the data from default SQL Server Instance, database named ShikshaNet with Windows Authentication.

Making Scrollable

Till now, we have designed a GridView with 3 columns, bind data to gridview. Let's move ahead and make it scrollable. Just go inside the code of GridView and add a style tag with below properties.

.... style="height:400px; overflow:auto" ...... 

You can change overflow:auto to overflow:scroll but that will show both Scrollbar and always. Above will show Vertical Scroll-bar only when the Height of GridView exceeds the assigned height.

We have done most of the task. Let's see its output in browser.

Let's scroll page to down.

Fixing Header

Now, data has been loaded, Gridview is showing perfect, it is scrolling in page also. Now it's time to remove its other drawback. Headers are not showing here while scrolling down. Let's apply this code so that header can be sticky or frozen at the top of gridview. Now write a CSS property using class selector method and apply for header in gridview.

CSS Selector will be as:

<style type="text/css">
        .FixedHeader {
            position: absolute;
            font-weight: bold;
        }     
    </style>   

Now apply this class in gridview as header style. GridView code will be like this:

 <asp:GridView ID="gvDistricts" runat="server" style="height:400px; overflow:auto" 
HeaderStyle-CssClass="FixedHeader" HeaderStyle-BackColor="YellowGreen" 
AutoGenerateColumns="false" AlternatingRowStyle-BackColor="WhiteSmoke" 
OnRowDataBound="gvDistricts_RowDataBound">   

Output of the above practice.

Oh! The first row of the gridview is overlapped with the header. While scrolling it will work fine but, we have to work on it to show the first row to user. Write the below code in RowDataBound event.

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");
     }
 }   

Let's see the final output.

Thanks for reading.  

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

John Bhatt
Software Developer (Senior) P.Yar.B Complex
Nepal Nepal
John Bhatt is an IT Professional having interest in Web technology. He is Web Designer, Developer, Software Developer, Blogger and Technology Geek. Currently he writes his Blogs at Blog of P.Yar.B and various other Sites. He is Main author and founder of Download Center.
Contact Him at : Facebook | Twitter | Website.
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralGud work PinmemberBinu198523-Jul-14 23:55 
GeneralGridView With Fixed Headers in Asp.Net Using C# and jQuery PinmemberBinu198512-Jun-14 20:27 
QuestionDoes not working Pinmemberharsha719-Mar-14 20:08 
AnswerRe: Does not working PinmemberJohn Bhatt20-Mar-14 3:18 
GeneralRe: Does not working Pinmemberharsha721-Mar-14 21:08 
GeneralRe: Does not working PinmemberJohn Bhatt25-Mar-14 3:19 
GeneralRe: Does not working PinmemberAkbar Sadakhathulla21-Apr-14 20:22 
GeneralRe: Does not working PinmemberJohn Bhatt23-Apr-14 4:32 
QuestionDoes not work Pinmemberdavid4life14-Mar-14 13:21 
AnswerRe: Does not work PinmemberJohn Bhatt14-Mar-14 19:57 
GeneralRe: Does not work Pinmemberdavid4life15-Mar-14 2:40 
GeneralRe: Does not work PinmemberJohn Bhatt20-Mar-14 3:19 
GeneralRe: Does not work Pinmemberdavid4life15-Mar-14 2:44 
GeneralRe: Does not work PinmemberJohn Bhatt20-Mar-14 3:16 
QuestionIE 8 rendering issues for "FixedHeader"? PinmemberJamie Fellrath13-Feb-14 4:35 
AnswerRe: IE 8 rendering issues for "FixedHeader"? PinmemberMember 1058100614-Apr-14 16:26 
GeneralRe: IE 8 rendering issues for "FixedHeader"? Pinmemberdf49422-Apr-14 4:50 
AnswerRe: IE 8 rendering issues for "FixedHeader"? PinmemberJohn Bhatt23-Apr-14 4:35 
SuggestionSmall C# code modification PinmemberCraigLG27-Jan-14 10:42 
GeneralRe: Small C# code modification PinmemberJohn Bhatt28-Jan-14 2:13 
QuestionGridView with Fixed Header and Scroll Bar PinmemberAdrian jaravete21-Jan-14 22:09 
AnswerRe: GridView with Fixed Header and Scroll Bar PinmemberJohn Bhatt21-Jan-14 22:35 
Questionproblem with the code PinprofessionalVinay Jade18-Jan-14 6:06 
AnswerRe: problem with the code PinmemberJohn Bhatt19-Jan-14 1:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140905.1 | Last Updated 18 Jan 2014
Article Copyright 2014 by John Bhatt
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid