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.
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
01 02 03 04 05 06 07 08 09 10 11 | 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.
1 2 3 4 5 6 7 8 | 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.
Similarly you can override the same thing in GridView_PreRender
Method as well
01 02 03 04 05 06 07 08 09 10 | 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; } } } |