Failed to populate DataGridView
I am population DataGridView 开发者_JAVA百科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 DataGridViewColumn
which 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.
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
datagridview1.Columns.Add(col);
or
DataGridViewColumn col= new DataGridViewColumn();
DataGridViewTextBoxCell cell = new DataGridViewTextBoxCell();
col.CellTemplate = cell;
datagridview1.Columns.Add(col);
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.
Like ASPMapper said in the comment below the original question, just set it. You don't even have to clear your columns before hand:
private void PopulateGridView(DataTable dt)
{
dataGridView1.DataSource = dt;
// notice if your DataTable is null, it simply clears the DataGridView control
}
your code crashes because DataGridViewColumn
does not provide a cell template ...
maybe you want to use one of those? (instead of the base DataGridViewColumn
)
DataGridViewButtonColumn
DataGridViewCheckBoxColumn
DataGridViewComboBoxColumn
DataGridViewImageColumn
DataGridViewLinkColumn
DataGridViewTextBoxColumn
on the other hand ... the DataGridView is capable of auto-creating the columns at runtime when a new datasource is provided ...
private void PopulateGridView(DataTable dt)
{
if (dt != null)
{
dataGridView1.Columns.Clear();
dataGridView1.DataSource = null;
dataGridView1.AutoGenerateColumns = true;
this.dataGridView1.DataSource = dt;
}
}
}
}
Is doing the job for me.
精彩评论