I am population DataGridView from DataTable, but getting following error:
At least one of the DataGridView
control’s columns has no cell template
private void PopulateGridView(DataTable dt)
{
if (dt != null)
{
dataGridView1.Columns.Clear();
dataGridView1.DataSource = null;
foreach (DataColumn col in dt.Columns)
{
//Declare the bound field and allocate memory for the bound field.
DataGridViewColumn datacolumn = new DataGridViewColumn();
//Initalize the DataField value.
datacolumn.DataPropertyName = col.ColumnName;
datacolumn.Name = col.ColumnName;
//Initialize the HeaderText field value.
datacolumn.HeaderText = col.ColumnName;
//Add the newly created bound field to the GridView.
this.dataGridView1.Columns.Add(datacolumn); // ** Error **
}
//Initialize the DataSource
this.dataGridView1.DataSource = dt;
}
The error you are seeing is because you are adding the base column type
DataGridViewColumnwhich has no cell template assigned. If the DataGridView was to try and assign a new cell for this column it would not know what to do.You can either choose to define the column type, or to set the column’s cell template to a cell.
or
There are several available column types.
However what you probably want to do is let the columns get autogenerated. With the DataGridView property AutoGenerate columns set to
true(the default) the columns are created when you assign the datasource.Adding columns programatically is often useful (for example adding a check box column to allow row selection) but in this case you shouldn’t need to do this.