我试图通过将代码放置在DataBound事件内来格式化GridView控件中的列。这是行不通的,因为出于某些原因未填充columns集合。该控件已绑定,它可以工作,但是column集合显示的计数为零,因此该代码不起作用。
有想法吗?
protected void gvReport_DataBound(object sender, EventArgs e)
{
for (int columnIndex = 0; columnIndex <= gvReport.Columns.Count - 1; columnIndex += 1)
{
var col = ((BoundField)gvReport.Columns[columnIndex]);
if (object.ReferenceEquals(col.DataField.GetType(), typeof(System.DateTime)))
col.DataFormatString = "MM/dd/yyyy";
}
}
生成的列在GridViewAutoGenerateColumns="true"
的Columns
集合中不可用。您可以在RowDataBound
事件处理程序中处理单元格:
protected void gvReport_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
object value = (e.Row.DataItem as DataRowView).Row.ItemArray[i];
if (value is DateTime)
{
TableCell cell = e.Row.Cells[i];
cell.Text = ((DateTime)value).ToShortDateString();
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句