I edit data in a DataTable which is bound to a DataGridView. When a new column is created in the DataTable a new column is generated in the view.
Ordinarily I would set the view column properties in a DataGridView_ColumnAdded event, however the default for the columns at present is to add a view column with SortMode set to Automatic which is incompatible with the DataGridView ColumnHeaderSelect property and causes an error before the column added event can fire.
I presume I get around this by defining a ‘template’ column for newly generated columns – but how?
OK, time to hack it:
To demonstrate, here’s a little app:
Basically, at first I set the DataGridView selection mode to ColumnHeaderSelect. On the button1 click, I add stuff to the datatable, and then bind it to the DataGridView. The trick is, that I call a method called FlipSelectionMode() before and after I bind the DGV. What this does, is if it’s in columnheaderselect mode it flips it to cell select and vice versa. That enables the column to be added. Then, in the column added event, I set the columns sort property to Programmatic, otherwise, you won’t be able to add another column. To demonstrate that, on the button2 click, it just adds another column, again while flipping the selection mode before and after.
I agree, this is a total hack, but the DGV is funky. I’ve had many many issues with it, and I almost always have to hack around stuff.