我正在使用下面的代码(部分代码)从网格行中打印出来。但是最后一列有金额。所以我想将最后一列对齐为右对齐。但是我得到了错误。
DataTable dt = (DataTable)ViewState["Datasource"];
DataTable newTable = dt.DefaultView.ToTable(false, "FLD_ID", "FLD_CUST_ID", "FLD_CUST_NAME", "FLD_CUST_ADDR", "FLD_AMT");
newTable.Columns["FLD_ID"].ColumnName = "PAY.ID";
newTable.Columns["FLD_CUST_ID"].ColumnName = "CUST.ID";
newTable.Columns["FLD_CUST_NAME"].ColumnName = "CUST.NAME";
newTable.Columns["FLD_CUST_ADDR"].ColumnName = "ADDRESS";
newTable.Columns["FLD_AMT"].ColumnName = "INV.AMOUNT";
GridView PrintGrid = new GridView();
PrintGrid.DataSource = newTable;
PrintGrid.DataBind();
PrintGrid.AllowPaging = false;
PrintGrid.Columns[4].ItemStyle.HorizontalAlign = HorizontalAlign.Right;
//Got Error Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index.
请帮我解决这个问题。
PrintGrid.Columns[4].ItemStyle.CssClass="alignright";
然后添加 CSS
.alignright{
text-align:right;
}
这是
您问题的解决方案。
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;
}
在行数据绑定事件中对齐
protected void GridView_RowDataBound(object o, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Right;
}
}
它对我有用的唯一方法是使用
e.Row.Cell[field_position].Style.Value = "text-align: right".
除了此代码之外,不需要更多工作。工作正常。即使一起使用,其他选项也不会生效。