Click here to Skip to main content
15,867,939 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

 
QuestionIt does not work when you have more columns Pin
atul1119-Jan-21 17:18
atul1119-Jan-21 17:18 
QuestionFixing headers widths Pin
wazodnuit20-May-20 19:55
wazodnuit20-May-20 19:55 
QuestionWebsite header Pin
Member 138147266-May-18 20:31
Member 138147266-May-18 20:31 
BugGridView with Fixed Header and Scroll Bar Pin
Member 1365091827-Mar-18 21:22
Member 1365091827-Mar-18 21:22 
QuestionAm I wrong about limitations to this approach? Pin
Plgy441-Feb-17 9:33
Plgy441-Feb-17 9:33 
AnswerRe: Am I wrong about limitations to this approach? Pin
John Bhatt20-Aug-17 5:33
professionalJohn Bhatt20-Aug-17 5:33 
QuestionOne more Issue Pin
nishant00931-Jul-16 22:19
nishant00931-Jul-16 22:19 
AnswerRe: One more Issue Pin
John Bhatt20-Aug-17 5:34
professionalJohn Bhatt20-Aug-17 5:34 
QuestionIts not working.. It just add the scroll to left but header does not remain visible when we scroll down. Pin
nishant00931-Jul-16 5:18
nishant00931-Jul-16 5:18 
AnswerRe: Its not working.. It just add the scroll to left but header does not remain visible when we scroll down. Pin
John Bhatt20-Aug-17 5:35
professionalJohn Bhatt20-Aug-17 5:35 
QuestionSeems like a duplicate Pin
DrABELL19-Feb-15 12:32
DrABELL19-Feb-15 12:32 
AnswerRe: Seems like a duplicate Pin
John Bhatt19-Feb-15 18:50
professionalJohn Bhatt19-Feb-15 18:50 
QuestionHeader width is not equal to Grid rows Pin
Member 1144165610-Feb-15 3:26
Member 1144165610-Feb-15 3:26 
QuestionWidth of Fixed Header in GridView Pin
Member 1144165610-Feb-15 2:57
Member 1144165610-Feb-15 2:57 
QuestionGridview with fixed header Pin
Member 1063459015-Jan-15 23:02
Member 1063459015-Jan-15 23:02 
QuestionHow to freeze the Footer Pin
Member 112278813-Dec-14 3:03
Member 112278813-Dec-14 3:03 
QuestionThe name 'gvDistricts' does not exist in the current context Pin
Member 1119353230-Oct-14 8:03
Member 1119353230-Oct-14 8:03 
AnswerRe: The name 'gvDistricts' does not exist in the current context Pin
John Bhatt3-Nov-14 19:09
professionalJohn Bhatt3-Nov-14 19:09 
QuestionHeader row width is not equal to Gridrow Pin
Member 1092449315-Oct-14 23:57
Member 1092449315-Oct-14 23:57 
thanks, this code helped me, but when im using this for my gridview the header row width is less than the grid row,Plz can u help me out to do this thank u Smile | :)
AnswerRe: Header row width is not equal to Gridrow Pin
John Bhatt3-Nov-14 19:11
professionalJohn Bhatt3-Nov-14 19:11 
SuggestionUsed CSS instead of the row bound event Pin
yohannn15-Oct-14 7:32
yohannn15-Oct-14 7:32 
GeneralRe: Used CSS instead of the row bound event Pin
John Bhatt3-Nov-14 19:12
professionalJohn Bhatt3-Nov-14 19:12 
QuestionDoes not working Pin
harsha719-Mar-14 20:08
harsha719-Mar-14 20:08 
AnswerRe: Does not working Pin
John Bhatt20-Mar-14 3:18
professionalJohn Bhatt20-Mar-14 3:18 
GeneralRe: Does not working Pin
harsha721-Mar-14 21:08
harsha721-Mar-14 21:08 

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.