. net GridView -你可以右对齐一个列吗?

本文关键字:一个 GridView 右对齐 net | 更新日期: 2023-09-27 17:49:47

您可以轻松地右对齐GridView中的一个列吗?

我有这个

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

它被绑定到一个有很多列的DataTable(动态生成的)。我只是想让'Price'列右对齐。

(遇到这个问题,我想知道我是否应该打印出HTML <table>而不是使用GridView。使用HTML,我可以完全控制。)

. net GridView -你可以右对齐一个列吗?

是的,你可以,但我认为如果你有AutoGenerateColumns设置为真(这是默认情况下),那么你需要使用RowDataBound事件右对齐列。作为旁注,如果更容易,您可以将AutoGenerateColumns设置为false并使用BoundFields,这将为您提供更多格式化选项,并可能消除对RowDataBound事件的需求。

GridView:

<asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound" runat="server"></asp:GridView>
后台代码:

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;
}

希望对你有帮助。

<Columns>
...
    <asp:BoundField DataField="Price" HeaderText="Price" 
        ItemStyle-HorizontalAlign="Right" ItemStyle-Width="80" />
...
</Columns>

即使这个问题是很久以前发布的,这可能会帮助你碰巧在这个页面结束的人。

给出的答案假设将应用对齐的列的索引是预先知道的,或者列是在设计时在.aspx页面上创建的;但情况并非总是如此。

对于寻找一个通用解决方案的人来说,其中列是自动生成的索引列的头' Price ' 事先不知道,这里是一个解决方案

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;
        }
   }
}

将ItemTemplate中的项放在一个div中,然后为该div设置样式。

<ItemTemplate>
<div id="divReportName">
<asp:Label ID="lblReport" runat="server" ></asp:Label>
</div>
</ItemTemplate>
// css for div
#divReportName { text-align: left;}

您可以使用ItemStyle-

在Boundfield内执行对齐

像这样:

<asp:BoundField DataField="SOH" HeaderText="SOH" SortExpression="SOH" ItemStyle-HorizontalAlign="Right"/>

这对我来说很有用,我需要在我的gridview

中只对齐特定的列

您是否将此添加到GridView的第一行?

OnRowDataBound="GridView1_RowDataBound"