Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing GridView column properties from code-behind

Tags:

I am creating a GridView in a method like so:

GridView gridView = new GridView();
gridView.DataSource = reportData.Tables[0];
gridView.DataBind();

I am later exporting it to Excel and it works great. The columns are being auto-generated from my source data. I would like to change the DataFormatString property of some of the columns however after I databind and before I export to Excel. I can't seem to find the correct property to change. Can anybody point me in the right direction?

like image 322
Mike Cole Avatar asked Jul 16 '09 20:07

Mike Cole


1 Answers

According to AutoGenerateColumns documentation:

This option provides a convenient way to display every field in the data source; however, you have limited control of how an automatically generated column field is displayed or behaves.

Note: Automatically generated bound column fields are not added to the Columns collection.

I tired looking for these AutoGeneratedFields with no luck.
I can think of several options to achieve that (from worst to best):

  1. Add an event to the grid (like RowDataBound), this will give you access to the rows' cells, but isn't too convenient.
  2. Don't use AutoGeneratedField Create these columns manually, as in:

    BoundField dateField = new BoundField();
    dateField.HeaderText = "Date";
    dateField.DataField = "date";
    dateField.DataFormatString = "{0:MMMM, yyyy}";
    gridView.Columns.Add(dateField); 
    

    This options gives you bes control over titles.

  3. Add another layer for data formatting and presentation. This is probably the best option. Also, that way you don't have to use DataTables, a GridView can by bound to any collection of objects with public properties (eg, to a List<Employee)), and AutoGeneratedField turns them into columns.
    I think this is the best option. Suppose you could access the auto columns, what then? You'd have to search for a column based on its name or index, which seems very messy, and increases coupling.

And, as a last note, you should think about creating Excel files by using the API. It's not as easy, but HTML XLS files are less compatible with Excel 2007 - it displays a warning message that the format of the file is incompatible with the extension, and worse, the file brakes if it is opened and saves (can be Save As though), making your files less user-friendly.

like image 129
Kobi Avatar answered Oct 12 '22 08:10

Kobi