Some time developers need a feature of fixed header to show thousands of data on the web pages.So, this tutorial will show how to fix header of control.Here, control can be repeater , gridview or any control which is using for showing data in asp.net.
For showing data , I am using repeater control and code will be like -
<asp:repeater id="Repeater1" runat="server">
<HeaderTemplate>
<table id="table12" width="505" style="table-layout: fixed; border:solid 1px black">
<thead>
<tr id="thead" style="width: 505px; background-color:#BEBEBE">
<td>Name</td>
<td>Mobile No</td>
<td>Address</td>
</tr>
</thead>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%#DataBinder.Eval(Container.DataItem, "Name")%>
</td>
<td>
<%#DataBinder.Eval(Container.DataItem,"MobileNo")%>
</td>
<td>
<%#DataBinder.Eval(Container.DataItem,"Address")%>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:repeater>
In repeater control, I have design a HTML table which will be used for containing bind data.Thing which should be noticed here is style which is defined in <table> with id 'table12'.
In style , 'table-layout' property is fixed due to which the horizontal layout only depends on the table's width and the width of the columns, not the contents of the cells.
Now,give boundry to repeater control , so that,fixed header effect can be noticed.
<div style="overflow: scroll; height: 100px; width: 505px">
<asp:repeater id="Repeater1" runat="server">
...............
</asp:repeater>
</div>
Create another <div> tag which will hold header column names dynamically.
<div id="tableHeader">
</div>
Now finally the magic part, a javascript code -
function fixHeader()
{
//get the id of table used in repeater control
var t = document.getElementById("table12");
var thead = t.getElementsByTagName("thead")[0];
var t1 = t.cloneNode(false);
t1.appendChild(thead);
tableHeader.appendChild(t1)
}
//call fixHeader() function on page load
window.onload = fixHeader
put this code in <script> tag in <head> section of web page.
Output will be something like -
I hope that this tutorial will help you somewhere.
Happy Coding !!!