Can you easily right-align just one column in a GridView?
I have this
Did you add this in the first line of the GridView
?
OnRowDataBound="GridView1_RowDataBound"
Even though the question posted long ago, this might help someone you happens to end up at this page.
The answers given assume that the index of the column to which the alignment will be applied is known in advance or the columns are created at design time on the .aspx page; but this is not always the case.
For someone looking for a general solution in which the columns are auto generated and the index of column with header ‘Price’ not known in advance, here is a solution
protected void grData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int i = ((DataTable)((GridView)sender).DataSource).Columns.IndexOf("Price");
for (int j = 0; j < e.Row.Cells.Count; j++)
{
if (j == i)
e.Row.Cells[j].HorizontalAlign = HorizontalAlign.Right;
else
e.Row.Cells[j].HorizontalAlign = HorizontalAlign.Left;
}
}
}
<Columns>
...
<asp:BoundField DataField="Price" HeaderText="Price"
ItemStyle-HorizontalAlign="Right" ItemStyle-Width="80" />
...
</Columns>
Enclose the item in the ItemTemplate in a div and then set styling to the div.
<ItemTemplate>
<div id="divReportName">
<asp:Label ID="lblReport" runat="server" ></asp:Label>
</div>
</ItemTemplate>
// css for div
#divReportName { text-align: left;}
Yes, you can, but I think if you have AutoGenerateColumns
set to true (which it is by default) then you need to right align the column using the RowDataBound
event. As a side note, if it's easier you can set AutoGenerateColumns
to false and use BoundFields which will give you more formatting options and will probably eliminate the need for the RowDataBound
event.
GridView:
<asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound" runat="server"></asp:GridView>
Codebehind:
protected void GridView1_RowDataBound(object o, GridViewRowEventArgs e)
{
//Assumes the Price column is at index 4
if(e.Row.RowType == DataControlRowType.DataRow)
e.Row.Cells[4].HorizontalAlign = HorizontalAlign.Right;
}
Hope that helps.
You can perform alignment within the Boundfield using ItemStyle-
like this :
<asp:BoundField DataField="SOH" HeaderText="SOH" SortExpression="SOH" ItemStyle-HorizontalAlign="Right"/>
This worked for me where i needed to align only specific columns in my gridview