Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET GridView - Can you right-align just one column?

Can you easily right-align just one column in a GridView?

I have this

<asp:GridView ID="GridView1" runat="server"></asp:GridView>

It is bound to a DataTable (generated dynamically) that has many columns. I just want the 'Price' column to be right-aligned.

(Coming across this problem, I am wondering if I should be printing out HTML <table> instead of using a GridView. Using HTML I would have total control.)

like image 576
Aximili Avatar asked Apr 13 '11 03:04

Aximili


People also ask

How do you align columns?

On the Home tab, click Paragraph, and then click Align. Select the Align with option and then select the paragraph tag pertaining to the column one paragraph.

How show multiple values in GridView single column?

Answers. Use a TemplateField. In the ItemTemplate tag, you've to put html corresponding to your UI requirements. You can put 2 link buttons.

Which type of columns can be added to GridView?

This column field type enables you to create a custom column field. Although you can programmatically add column fields to the Columns collection, it is easier to list the column fields declaratively in the GridView control and then use the Visible property of each column field to show or hide each column field.


2 Answers

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.

like image 119
rsbarro Avatar answered Sep 20 '22 19:09

rsbarro


<Columns>
...
    <asp:BoundField DataField="Price" HeaderText="Price" 
        ItemStyle-HorizontalAlign="Right" ItemStyle-Width="80" />
...
</Columns>
like image 43
IrishChieftain Avatar answered Sep 20 '22 19:09

IrishChieftain