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.

  1. 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. I’ve updated the sources so that you can hide/unhide the regular GlobalSalesRows:

    datagridview hiding rows
    datagridview showing rows

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>