InvalidOperationException: This operation cannot be performed while an auto-filled column is being resized
This seems to be a bug - the code is trying to access dataGridView.TopLeftHeaderCell
, which when happens for the first time actually creates that cell and triggers some layout actions not expected at that moment.
With all that in mind, the fix is simple. We need to make sure that the TopLeftHeaderCell
is created before DataGridView
handle, by adding the following line (before addding the grid to Controls
for instance)
var topLeftHeaderCell = grid.TopLeftHeaderCell; // Make sure TopLeftHeaderCell is created
Thank you, Ulf, for the excellent sample showing how to reproduce this. One of my clients reported this bug to me and your sample has been invaluable.
Taking Ivan's excellent answer one step further, creating your own grid inheriting from the DataGridView
should prevent this ridiculous bug permanently. Just be sure to always use the custom grid throughout your application.
public class Grid
: DataGridView
{
protected override void OnHandleCreated(EventArgs e)
{
// Touching the TopLeftHeaderCell here prevents
// System.InvalidOperationException:
// This operation cannot be performed while
// an auto-filled column is being resized.
var topLeftHeaderCell = TopLeftHeaderCell;
base.OnHandleCreated(e);
}
}