To create a scrolling grid that will retain position after postback (only for IE)

To create a scrolling grid that will retain position after postback (only for IE)

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

  1. Set the useaccessibleheader to true for the datagrid:


    <asp:datagrid id=”DataGrid1″ runat=”server” useaccessibleheader=”True” />

  2. 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” />

  3. 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)”;

  }

}

  1. Register client side javascript for 2 things:
    1. Store that top of the item when scrolled
    2. Reset the top to the scroll position after postback


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>”);

}

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

Comments are closed.