65.9K
CodeProject is changing. Read more.
Home

Hide DataGridView columns with no data in any row

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

May 4, 2011

CPOL
viewsIcon

9191

Hello,You loop through all the rows, even when you know that the column will be visible (i.e., when the first non-empty cell is found), resulting in time loss and lots of unneeded variable assigments.A second remark is that a hidden column will never be shown later, even if some data is...

Hello, You loop through all the rows, even when you know that the column will be visible (i.e., when the first non-empty cell is found), resulting in time loss and lots of unneeded variable assigments. A second remark is that a hidden column will never be shown later, even if some data is present in one of the hidden cells. I'm not familiar with C#, but I think that the following code could be an improvement. Philippe
public static DataGridView RemoveEmptyColumns(this DataGridView grdView)
 {
     foreach (DataGridViewColumn clm in grdView.Columns)
     {
         bool visibility = false;
         foreach (DataGridViewRow row in grdView.Rows)
         {
             if (row.Cells[clm.Index].Value.ToString() != string.Empty)
             {
                 visibility = true;
                 break;
             }
         }
         grdView.Columns[clm.Index].Visible = visibility;
     }
     return grdView;
 }