Friday, 18 May 2007

Adding columns dynamically to a data grid control

Ok just a quick note here for the future. To add columns (i.e. bound or template etc) columns to a datagrid use the following:-

make sure the autogenerate on the data grid is switched off.


then loop over the columns in the data source table.

foreach (DataColumn dc in dataTable.Columns)
BoundColumn newColumn = new BoundColumn();
newColumn.DataField = dc.ColumnName;
newColumn.HeaderText = ;



If you autogenerate the columns then the columns collection on the data grid will have no items.