Click here to Skip to main content
15,904,655 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Hide DataGridView columns with no data in any row

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
8 May 2011CPOL 9.1K   2  
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)


Written By
Belgium Belgium
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --