I was able to reproduce the issue. The Clear
method call is just fine, you can remove columns one by one and the issue still persists. The "offending" call is surprisingly Add
:
col.Visible = false; // Notice the visibility of this column...
if (col.Visible)
{
// Just to be sure. Never get here.
}
dataGridView1.Columns.Add(col);
if (col.Visible)
{
// Surprise! We are here.
}
Why this behavior occurs?
It's definitely a bug. The issue is happening only and only if all the following conditions are met:
DataGridView
is in bound mode, i.e. hasDataSource
set. The data source type doesn't matter.Columns
collection is emptyAdd
method is called with a column havingVisible = false
In this case the code hits an internal class DataGridViewDataConnection
method MatchCurrencyManagerPosition
. Take a look at the source code, especially the
// Treat case where columnIndex == -1. We change the visibility of the first column.
comment and the code block after that comment.
How to avoid it
To recap, this is happening only in data bound mode and only for the first added column if it is set to be hidden.
So there are a couple ways to fix that:
Make sure the grid is not in bound mode when repopulating columns
var dataSource = dataGridView.DataSource; dataGridView.DataSource = null; // Repopulate columns //... dataGridView.DataSource = dataSource;
Don't use
Add
method. Create all columns and keep them in either variables or temporary list, and at the end use theAddRange
method which has no such effect.Do not set
Visible = false
in advance. Create and add all the columns, then hide the desired ones.