I have seen a lot of posts on SO about weird behaviour of Columns and their visibility in particular when refreshing the grid and dynamically building the columns in the list, but haven't found a satisfactory solution.
After some digging I am almost certain this issue is due to the use of the DataGridView.Columns.Clear()
method.
So far I haven't been able to work out why but removing the Clear() method when I dynamically build my DataGridView Columns stops hidden columns from appearing, but I don't understand why this would have any affect? Surely if you clear the Columns collection and use DataGridView.Columns.Add()
to start adding new ones, code like;
dataGridView1.Columns.Clear(); // This is the offending method!!
dataGridView1.AutoGenerateColumns = false;
dataGridView1.ShowEditingIcon = false;
dataGridView1.RowHeadersVisible = false;
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
col.DataPropertyName = "ID";
col.HeaderText = "ID";
col.Visible = false; // Notice the visibility of this column...
dataGridView1.Columns.Add(col);
... // Code is repeated for other columns in the collection
I can't see anything wrong with but if dataGridView1.Columns.Clear();
is included at the beginning my hidden column becomes visible, surely this is a bug?
Refresh()
which is more or less the same thing. Behaves the same way... – DipsomaniaDataTable dtEmpty=new DataTable(); dataGridView1.DataSource = dtEmpty;
or simplydataGridView1.DataSource = null
; – AlithiadataGridView1.DataSource = null;
but as I'm not usingdataGridView1.AutoGenerateColumns = true;
this has no affect. Plus for reference I'm using Entity Framework with Repository pattern for my data. – Dipsomania