DataGridView changes column visibility

G

Guest

If you create a DataGridView and add a hidden column to it (a column with
its visible property set to false), the DataGridView will make the column
visible anyway if you make changes to the data source.

For an example of this behavior, crate a new windows form project and
place a DataGridView control on the form. Add this one line of code to the
form class:

private DataTable dt;

Put the following code in the Load event for the form:

// primary key column
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.DataPropertyName = "primarykey";
column.HeaderText = "primarykey";
column.Visible = false;
dataGridView1.Columns.Add(column);
// value column
column = new DataGridViewTextBoxColumn();
column.DataPropertyName = "value";
column.HeaderText = "value";
column.Visible = true;
dataGridView1.Columns.Add(column);
// create DataTable and set as the DataGridView's DataSource
dt = new DataTable();
dt.Columns.Add(new DataColumn("primarykey",typeof(int)));
dt.Columns.Add(new DataColumn("value", typeof(string)));
dataGridView1.DataSource = dt;

If you run the project, everything will look good. Now, put a button on
the form and add the following code to its click event:

dataGridView1.DataSource = null;
dataGridView1.DataSource = dt;

Now run the program. When you click on the button, suddenly the invisible
column becomes visible. This doesn’t just happen when you change the
datasource, but also happens if the data source is a DataView and you filter
the records, etc. Has anyone else encountered this and does anyone know if
there is a fix for it?
 
G

Guest

I have a smiliar problem, but I only refill the dataset and never touch the
bindingsource. When I refill the dataset, the datagridview column (being the
primary key of the table) changes visibility.

I'm thinking it's some behaviour of the datagrid when the columns are
autogenerated, with special treatment for keys. That's my what I'm thinking,
but I have not found a solution yet, or a cause for the behaviour!

Richard
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top