.NET GridView – 你能正确对齐一列吗?

你能轻松地在GridView中右对齐一列吗?

我有这个

 

它绑定到具有许多列的DataTable(动态生成)。 我只想让“价格”栏右对齐。

(遇到这个问题,我想知道我是否应该打印HTML

而不是使用GridView。使用HTML我会完全控制。)

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

网格视图:

  

代码隐藏:

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

希望有所帮助。

  ...  ...  

即使很久以前发布的问题,这可能会帮助您碰巧在此页面上遇到问题。

给出的答案假定预先知道要应用对齐的列的索引,或者在.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; } } } 

将项目包含在div中的ItemTemplate中,然后将样式设置为div。

  
// css for div #divReportName { text-align: left;}

您可以使用ItemStyle-在Boundfield中执行对齐

像这样 :

  

这对我来说很有用,我需要在gridview中只对齐特定的列

你是否在GridView的第一行添加了这个?

 OnRowDataBound="GridView1_RowDataBound"