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

5.00/5 (1 vote)
4 May 2011CPOL 8.9K  
I hate to be overly critical, but variable names of flag1 and flag2 are poor choices. Use a name that tells the reader what it actually represents (e.g FoundData). Perhaps better naming options would help you see that flag2 will never be anything other than True, and is completely unnecessary....
I hate to be overly critical, but variable names of flag1 and flag2 are poor choices. Use a name that tells the reader what it actually represents (e.g FoundData). Perhaps better naming options would help you see that flag2 will never be anything other than True, and is completely unnecessary.

My second thought is that as soon as a non Empty value is found, you should break out of the FOR loop, to avoid trawling through all the remaining data rows for no reason.

My next thought is wondering whether DbNull values would fall through the logic if using a DB data table.

My last thought is that if I used this logic, then users would assume there was an application issue, showing an entirely empty column is telling the user something.


This really should just be (not tested, just typed in):

foreach (DataGridViewColumn clm in grdView.Columns)
{
    Bool FoundData = false;
    foreach (DataGridViewRow row in grdView.Rows) 
    {
         if (row.Cells[clm.Index].Value.ToString() != string.Empty)
         {
             FoundData = true;
             break;
         }
    }
    if (!FoundData)
    {
         grdView.Columns[clm.Index].Visible = false;
    }
}

License

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