Wednesday, July 15, 2009

Styling alternating blocks in .Net GridView

ASP.Net has some cool support for alternating row styles but what if you wanted to style based on alternating row 'groups' (something logically defined and irregular) rather than just by alternating row index?



I had that challenge to solve and after a weekend on the river in northern Kentucky with the fam, felt like I was up to it this morning. I still want the same styles to apply for the entire GridView but wanted to set the background color conditionally to a type of gray for the alternating block.

I decided on a style toggle approach that would require very little code in my c# code-behind file.

with member variables for the currentBlock and the current style toggle, string and int respectively, I accomplished this very simply

protected void SetMyStyle(Object sender, GridViewRowEventArgs e)
{
MetasolvData.CLRDesignLine tempLine;
if (e.Row.DataItem != null)
{
tempLine = (MetasolvData.CLRDesignLine)e.Row.DataItem;
if (tempLine.BlockInd != currentBlock)
{
currentBlock = tempLine.BlockInd;
styleToggle = (styleToggle == 0) ? 1 : 0;
}
e.Row.BackColor = (styleToggle == 0) ? System.Drawing.Color.LightGray : System.Drawing.Color.White;
}
}

and then my GridView just uses the SetMyStyle operation in its onRowDataBound event


RowStyle-CssClass="mGrid"
HeaderStyle-CssClass="mGrid"
PagerStyle-CssClass="mGrid" OnRowDataBound="SetMyStyle"
EmptyDataText="No Design Lines exist for this CLR"
EmptyDataRowStyle-CssClass="mGrid">

















No comments: