Monday, November 29, 2010

Freeze Columns and Header Row

Last week, I got headache for freezing the first column and the header row in gridview. So I researched to fix the columns and row simultaneously by setting the <div> width, height and scroll as auto. And I write some in stylesheet and I did add some code in code behind. Finally, my griview got fixed columns and fixed rows. Below is the steps to do:

Step1 :  StyleSheet1.css
/* Div container to wrap the datagrid */
div#gridviewstyle {
width: 850px;
height: 400px;
overflow: scroll;
border: solid 1px black;
}

/* Locks the left column */.testlock{color:#5E9709;
background-color:#D6F4DC;
border-right: 1px solid silver;
text-align:center;
position:relative;
width:20%;
cursor: default;
 left: expression(document.getElementById("gridviewstyle ").scrollLeft-2);
}

 /* Locks table header */
.testlockvertical
{
background-color:#D6F4DC;

text-align:center;
border-right: 1px solid silver;
position:relative;
cursor: default;
top: expression(document.getElementById("gridviewstyle ").scrollTop-2);
z-index: 99px;
}


Step2 : Default.aspx
We declare StylSheet1.css to our web page. So we can use the styles in that stylesheet.
<link href="../../StyleSheet1.css" rel=stylesheet type="text/css" />

<div id="gridviewstyle">
<asp:GridView id="GridView1" runat="server" CssClass="Grid" UseAccessibleHeader="True" AutoGenerateColumns=True OnRowDataBound="GridView1_RowDataBound1">
</asp:GridView>
</div>


Step3 : Default.aspx.cs
/* For Autogenerated first columns freezing*/

protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e){
e.Row.Cells[0].CssClass = "testlock";
e.Row.Cells[0].Width = Unit.Pixel(200);
}

Step4 : Default.aspx.cs
/* I put the binding gridview as seperate function.*/
/* For Autogenerated Header rows freezing.*/
private void binddata(DataView dv)
{
      GridView1.DataSource=dv;
      GridView1.DataBind();

      GridView1.HeaderRow.CssClass = "testlockvertical"
      GridView1.HeaderRow.Cells[0].CssClass =
"testlock";
}

That's all. After that, you can see your gridview first column and header row are freezing.

HAPPY CODING!!!!!!!!!

No comments:

Post a Comment

If this post is useful, pls comment here.