1

I'm trying to format columns in the GridView control by placing code inside the DataBound event. It doesn't work, because for some reason the columns collection is not populated. The control is bound, it works, but yet the columns collection is showing a count of zero, and so the code doesn't work.
Ideas?

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

1 Answer 1

1

The columns generated with AutoGenerateColumns="true" are not available in the Columns collection of the GridView. You can process the cells in the RowDataBound event handler:

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();
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.