How to change GridView column alignments for dynamic data source ?

By | February 5, 2011

By default ASP.NET GridView Columns has left alignment text. We can use GridView ItemStyle property with either of GridView BondField or Template Field to change the default alignments.GridView properties,ItemStyle-HorizontalAlign having few set of values, using  which we can change the alignments.

image

Above customization is true when you are using Bound Field or Template Field for binding the data . But If you want to customize the same set alignments for data source which are directly binding with GridView you have to use Gridview_RowDataBound or Gridview_PreRender methods .

Let’s say you are binding below set of records directly with gridview

List<Employee> employees = new List<Employee>
{
new Employee{ID=1, Name="Employee 1", Address="Address 1" },
new Employee{ID=2, Name="Employee 2", Address="Address 2" },
new Employee{ID=3, Name="Employee 3", Address="Address 3" },
new Employee{ID=4, Name="Employee 4", Address="Address 4" },
new Employee{ID=5, Name="Employee 5", Address="Address 5" },
new Employee{ID=6, Name="Employee 6", Address="Address 6" }
};
GridView1.DataSource = employees;
GridView1.DataBind();

As the above set of records binded without any data bound field, you have to override the RowDataBound Event to set the alignment.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Right

}
}

DataControlRowType enum having the similar values as ItemStyle-Horizontal alignment.

image

Similarly you can override the same thing in GridView_PreRender Method as well


protected void GridView1_PreRender(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
row.Cells[0].HorizontalAlign = HorizontalAlign.Left;
}
}
}