Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Hide DataGridView columns with no data in any row

4.20/5 (7 votes)
8 May 2011CPOL 59.8K  
How to remove columns' visibility when their rows in the column are empty in DataGridView control
Here, I have developed a new feature in datagridview control with the help of an extension method.

Suppose you created a dynamically generated datagridview which contains 'n' number of columns per row. This method is to help to hide columns when all rows values for that column are empty.

Code using DataGridView extension method RemoveEmptyColumns() is below:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyProject
{
    public static class ExtensionGridView
    {
        public static DataGridView RemoveEmptyColumns(this DataGridView grdView)
        {
            foreach (DataGridViewColumn clm in grdView.Columns)
            {
                bool notAvailable = true;

                foreach (DataGridViewRow row in grdView.Rows)
                {
                    if (! string.IsNullOrEmpty(row.Cells[clm.Index].Value.ToString()))
                    {
                        notAvailable = false;
                        break;
                    }                   
                }
                if (notAvailable)
                {
                    grdView.Columns[clm.Index].Visible = false;
                }
            }

            return grdView;
        }
    }
}


Call RemoveEmptyColumns() in your datagridview:
DataGridView1.RemoveEmptyColumns();

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)