Public ReadOnly Property Columns() As DataGridViewColumnCollection
I then place my new user control on a Windows form and try to edit the columns using the designer. As soon as i click the add button to add a column, I get the following error: "At least one of the DataGridView control's columns has no cell template."
Firstly, the reason why this error occur is that new column has not been assigned with specific CellType (Column.CellType == null). The Designer’s Property Explorer does not provide a UI for editing new column’s CellType, because we are using the common collection editor.
Please let me introduce the reason why:
We can see DataGridView.Columns in Property Explorer “as same as” other collection properties, but it’s not entirely true. DataGridViewColumnCollection has extended the behavior of this collection property, and has added some custom UITypeEditor for it: DataGridViewColumnCollectionEditor, which has a class member called DataGridViewColumnCollectionDialog, as you can see like this:
The most important thing is: all DataGridViewColumn’s basic settings are being set within this dialog box (like CellType). Then new column initiated.
If we just treat DataGridViewColumnCollection as a common collection, there would not be any dialog box pop up allowing us to set new column’s properties.
Now, finding solutions or workarounds:
1.Add this DataGridVewColumnCollectionEditor to “Columns” directly like the following: Impossible
The reason why impossible is that all DataGridViewColumnCollectionEditor need to make sure the container of ColumnCollection is DataGridView. You know, UserControl containing a Columns property will not be treated as DataGridView, hence, we cannot add the designer attribute code for Columns like the following:
2.Workaround: add a collection into UserControl, create a custom CollectionEditor for edit this collection, and after that, mapping edited collection into DataGridView.Columns.
This solution should work. However, it may take some time do finish it.