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

0.00/5 (No votes)
8 May 2011CPOL 9.2K  
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

C#
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;
 }

License

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