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.

dataGrid1.AutoGenerateColumns=false;

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 = ;

dataGrid1.Columns.Add(newColumn);
}

etc.

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