Click here to Skip to main content
15,867,568 members
Articles / Web Development / CSS

GridView with Fixed Header and Scroll Bar

Rate me:
Please Sign up or sign in to vote.
4.69/5 (31 votes)
18 Jan 2014CPOL3 min read 406K   7.7K   42   45
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.NET
  <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.

C#
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.

CSS
.... 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.

Image 1

Let's scroll page to down.

Image 2

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:

CSS
<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.NET
 <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.

Image 3

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.

C#
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.

Image 4

Thanks for reading.  

License

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


Written By
Founder 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 | PRB - Blog.

Comments and Discussions

 
GeneralRe: Does not working Pin
John Bhatt25-Mar-14 3:19
professionalJohn Bhatt25-Mar-14 3:19 
GeneralRe: Does not working Pin
Akbar Sadakhathulla21-Apr-14 20:22
Akbar Sadakhathulla21-Apr-14 20:22 
GeneralRe: Does not working Pin
John Bhatt23-Apr-14 4:32
professionalJohn Bhatt23-Apr-14 4:32 
QuestionDoes not work Pin
david4life14-Mar-14 13:21
david4life14-Mar-14 13:21 
AnswerRe: Does not work Pin
John Bhatt14-Mar-14 19:57
professionalJohn Bhatt14-Mar-14 19:57 
GeneralRe: Does not work Pin
david4life15-Mar-14 2:40
david4life15-Mar-14 2:40 
GeneralRe: Does not work Pin
John Bhatt20-Mar-14 3:19
professionalJohn Bhatt20-Mar-14 3:19 
GeneralRe: Does not work Pin
david4life15-Mar-14 2:44
david4life15-Mar-14 2:44 
GeneralRe: Does not work Pin
John Bhatt20-Mar-14 3:16
professionalJohn Bhatt20-Mar-14 3:16 
QuestionIE 8 rendering issues for "FixedHeader"? Pin
Jamie Fellrath13-Feb-14 4:35
Jamie Fellrath13-Feb-14 4:35 
AnswerRe: IE 8 rendering issues for "FixedHeader"? Pin
Member 1058100614-Apr-14 16:26
Member 1058100614-Apr-14 16:26 
GeneralRe: IE 8 rendering issues for "FixedHeader"? Pin
df49422-Apr-14 4:50
df49422-Apr-14 4:50 
AnswerRe: IE 8 rendering issues for "FixedHeader"? Pin
John Bhatt23-Apr-14 4:35
professionalJohn Bhatt23-Apr-14 4:35 
SuggestionSmall C# code modification Pin
CraigLG27-Jan-14 10:42
CraigLG27-Jan-14 10:42 
GeneralRe: Small C# code modification Pin
John Bhatt28-Jan-14 2:13
professionalJohn Bhatt28-Jan-14 2:13 
QuestionGridView with Fixed Header and Scroll Bar Pin
Adrian jaravete21-Jan-14 22:09
Adrian jaravete21-Jan-14 22:09 
AnswerRe: GridView with Fixed Header and Scroll Bar Pin
John Bhatt21-Jan-14 22:35
professionalJohn Bhatt21-Jan-14 22:35 
Questionproblem with the code Pin
Vinay Jade18-Jan-14 6:06
professionalVinay Jade18-Jan-14 6:06 
AnswerRe: problem with the code Pin
John Bhatt19-Jan-14 1:51
professionalJohn Bhatt19-Jan-14 1:51 

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

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