【问题标题】:ASP.Net GridView Web Control Format ColumnsASP.Net GridView Web 控件格式列
【发布时间】:2016-07-21 00:39:00
【问题描述】:

我试图通过在 DataBound 事件中放置代码来格式化 GridView 控件中的列。它不起作用,因为由于某种原因,未填充列集合。控件已绑定,它可以工作,但列集合显示计数为零,因此代码不起作用。
想法?

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

【问题讨论】:

    标签: asp.net gridview


    【解决方案1】:

    使用AutoGenerateColumns="true" 生成的列在GridView 的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();
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-10-26
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-11
      • 1970-01-01
      • 2012-06-07
      相关资源
      最近更新 更多