65.9K
CodeProject is changing. Read more.
Home

Hide DataGridView columns with no data in any row

May 2, 2011

CPOL
viewsIcon

59975

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:
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();