To create a scrolling grid that will retain position after postback (only for IE)
- Add a div tag around the datagrid as follows:
<div style=”overflow: auto; height: 75px” id=”scrollGrid” runat=”server” onscroll=”updateScroll(this);”>
<asp:datagrid id=”DataGrid1″ runat=”server” useaccessibleheader=”True” />
</div>
-
Set the useaccessibleheader to true for the datagrid:
<asp:datagrid id=”DataGrid1″ runat=”server” useaccessibleheader=”True” /> -
Add a hidden field to maintain the scroll position. It must have runat attribute set to server to maintain value between postbacks:
<input type=”hidden” id=”scrollTop” runat=”server” /> - In the datagrid ItemDataBound event add the following:
private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) {
if (e.Item.ItemType == ListItemType.Header) {
e.Item.Attributes[“style”] = “position:relative; top:expression
(this.offsetParent.scrollTop);”;
}
else if (e.Item.ItemType == ListItemType.Footer) {
//e.Item.Attributes[“style”] = “position:relative; top:expression(this.offsetParent.clientHeight – this.offsetParent.scrollHeight + this.offsetParent.scrollTop + 40)”;
}
}
-
Register client side javascript for 2 things:
- Store that top of the item when scrolled
- Reset the top to the scroll position after postback
- Store that top of the item when scrolled
private void RegisterScrollScript() {
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(“<script type=\”text/javascript\”>”);
sb.Append(” function updateScroll(gridDiv) {“);
sb.Append(” document.getElementById(\”” + scrollTop.ClientID + “\”).value = gridDiv.scrollTop;”);
sb.Append(” }”);
sb.Append(” function setContentScrollPos(gridDiv) {“);
sb.Append(” document.getElementById(gridDiv).scrollTop = document.getElementById(\”” + scrollTop.ClientID + “\”).value;”);
sb.Append(” }”);
sb.Append(“</script>”);
RegisterClientScriptBlock(“MaintainScrollPos”, sb.ToString());
RegisterClientScriptBlock(“SetScrollPos”, “<script type=’text/javascript’>setContentScrollPos(‘” + scrollGrid.ClientID + “‘);</script>”);
}
- The following javascript gets rendered:
<script type=”text/javascript”>
function updateScroll(gridDiv) {
document.getElementById(“scrollTop
“).value = gridDiv.scrollTop;
}
function setContentScrollPos(gridDiv) {
document.getElementById(gridDiv).scrollTop = document.getElementById(“scrollTop”).value;
}
</script>
<script type=’text/javascript’>
setContentScrollPos(‘scrollGrid’);
</script>