Hide and unhide columns (or rows) in the DataGridView

Once in a while i see the following question:

I have to create a customized datagridview to enable the expandable columns. Expandable column in the sense drilling down the columns…. One column can hide multiple columns. The user can see the child columns by clicking the + button before the column name

Using the Visibile property of the DataGridViewColumn makes this a no-brainer. Let’s take the Databound DataGridView and implement functionality to hide/unhide the quarterly results. All you have to do is add a DataGridViewButtonColumn and handle the DataGridView CellClick event as following:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
 if (e.ColumnIndex == this.ColumnButton.Index)
 {
  bool visible = !this.ColumnQ1.Visible;
  this.ColumnQ1.Visible = visible;
  this.ColumnQ2.Visible = visible;
  this.ColumnQ3.Visible = visible;
  this.ColumnQ4.Visible = visible;
  this.ColumnButton.HeaderText = visible ? "-" : "+";
 }
}

This is how it looks like:

screenshot of datagridview hiding columns screenshot of datagridview unhiding columns

Feel free to download the updated source code for DataGridViewDataSource.zip.

This entry was posted on Saturday, January 13th, 2007 at 03:00 and is filed under C#, Windows Forms. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

2 Responses to “Hide and unhide columns (or rows) in the DataGridView”

  1. Nehme Gedeon says:

    Hello,

    Thanks for the interesting article, but while trying to implement a similar thing to rows, i couldn’t find a class called dataGridViewButtonRow …

    any hints?

    Thanks

  2. timvw says:

    I’ve updated the sources so that you can hide/unhide the regular GlobalSalesRows:

    datagridview hiding rows
    datagridview showing rows