ASP.NET GridView in scrollable DIV: Show selected row on click

By Peter Bromberg

Often you want to put your GridView inside a DIV tag with style overflow:auto This shows your GridView inside a box and provides scrollbars to enable you to scroll down and select a row. It conserves page real estate where you do not want to use Paging on your GridView. But if you click on a row, how to keep the selected row in focus after a postback? Here is a simple solution:

<script type="text/javascript">
window.onload = function(){
var strCook = document.cookie;
var intS = strCook.indexOf("!~");
var intE = strCook.indexOf("~!");
var strPos = strCook.substring(intS+2,intE);
document.getElementById('<%=grid1Div.ClientID %>').scrollTop = strPos;
function SetDivPosition(){
var intY = document.getElementById('<%=grid1Div.ClientID %>').scrollTop;
document.title = intY;
document.cookie = "yPos=!~" + intY + "~!";

<!-- This div will create scrollbars so that only a certain number of GridView rows are shown.
<div id="grid1Div" runat="server" style="overflow:auto; height:345px; width: 1300px;" onscroll="SetDivPosition()">

<asp:GridView ID="yourGrid" runat="server" Height="162px" Width="1275px" ...

protected void yourGrid_RowDataBound(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
Page.ClientScript.GetPostBackEventReference(sender as GridView,
"Select$" + e.Row.RowIndex.ToString()));

protected void yourGrid_RowSelectionChanged(object sender, EventArgs e)
// this is fired from a postback when user clicks on a row in your grid

GridViewRow row = this.gridDocket.SelectedRow;
int y = row.DataItemIndex; // this is the index into your DataBound collection.
// your logic here

Download the code sample here

ASP.NET GridView in scrollable DIV: Show selected row on click  (3849 Views)