ASP.NET GridView': Align Right Numerical Values from Code Behind

Tuesday, November 30, 2010

While creating generic user controls having GridViews, its not easy to format columns based on data the columns will have. The type of the data a column will have is not always known until the data is bounded on to the grid. The data on the GridView looks a lot better, when numerical values, dollar/currency amounts, percentages etc. are aligned to the right of the cells. This could be easily accomplished using the RowDataBound event of the GridView and then matching the cell value to a regular expression to determine if it matches your criteria for alignment.

Here is a sample implementation for a RowDataBound method for the GridView, which looks for cells having only numbers, comma (,) and a period(.) in the contents and if it finds a match, it aligns it to the right:

// C#
protected void gridViewt_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Right align the column if its a numerical value
for (int i = 0; i < e.Row.Cells.Count; i++)
{
if(Regex.IsMatch(e.Row.Cells[i].Text.Trim(), @"^[0-9,.]*$"))
{
e.Row.Cells[i].HorizontalAlign = HorizontalAlign.Right;
}
}
}
}
>
' VB.Net
Protected Sub gridViewt_RowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
' Right align the column if its a numerical value
For i As Integer = 0 To e.Row.Cells.Count - 1
If Regex.IsMatch(e.Row.Cells(i).Text.Trim(), "^[0-9,.]*$") Then
e.Row.Cells(i).HorizontalAlign = HorizontalAlign.Right
End If
Next
End If
End Sub

You can change the regular expression depending on what all do you you want to match to align the data to the right.