Click here to Skip to main content
15,867,453 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.
5.00/5 (1 vote)
4 May 2011CPOL 8.5K   3   1
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)


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

Comments and Discussions

 
GeneralEdit: fixed obvious syntax error Pin
Indivara4-May-11 3:28
professionalIndivara4-May-11 3:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.