Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

GridView with Fixed Header and Scroll Bar

0.00/5 (No votes)
18 Jan 2014 1  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here