Click here to Skip to main content
Click here to Skip to main content

Hide DataGrid Columns via HeaderText

By , 20 Jul 2005
 

Introduction

Many ASP.NET applications utilize the DataGrid control. This control provides the ability to dynamically hide or show a DataGridColumn by using the index of the column contained in the DataGridColumnsCollection. For example, if you want to hide the first column in a grid, you can do so by DataGrid.Columns[0].Visible = false;. A problem I ran into using the column index was when the columns had to be reordered. This can be a nightmare, especially if you have a lot of columns in your grid. Imagine a grid with 20+ columns and you need to move the 11th one to the 5th position and the 20th column to the 2nd position and so on. Every time you do this, you need to modify the column index reference in your code.

I thought to myself, "there has to be a way to retrieve a column by its name". Well, there is no DataGrid.Columns["Name"] attribute available but, there is Column.HeaderText. Even if you decide not to display the Header, the HeaderText value is still available if you set it. To access the HeaderText in your code-behind, simply loop through the DataGrid columns and check the HeaderText.

The Code

Below is an example of the method that dynamically hides and displays the columns. In my example solution, I call the HideShowColumns after I bind the DataTable to the grid.

private void HideShowColumns(DataGrid dg)
{
    if(dg == null)
    {
        return;
    }
    // Loop through all of the columns in the grid.
    foreach(DataGridColumn col in dg.Columns)
    {
        // Are we in UserView Mode?
        if(this.lblUiView.Text == UserView.User.ToString())
        {
            // Hide the Salary and SS# Columns.
            if(col.HeaderText == "Salary" || col.HeaderText == "SS#")
            {
                col.Visible = false;
            }
        }
        // Are we in AdminView Mode?
        else if(this.lblUiView.Text == UserView.Admin.ToString())
        {
            // Show the Salary and SS# Columns.
            if(col.HeaderText == "Salary" || col.HeaderText == "SS#")
            {
                col.Visible = true;
            }
        }
    }
}

Below, is a more simplistic version of the HideShowColumns. I removed the code related to my example solution so you can get a real clear view of the example. As you can see, it is a very simple solution. The code below will hide a column with a HeaderText of "ExampleColumn".

private void HideShowColumns(DataGrid dg)
{
    if(dg == null)
    {
        return;
    }
    // Loop through all of the columns in the grid.
    foreach(DataGridColumn col in dg.Columns)
    {
        // Hide the Salary and SS# Columns.
        if(col.HeaderText == "ExampleColumn")
        {
            col.Visible = false;
        }
    }
}

DataGrid's HTML

For my example, I added the HeaderText for each of the columns in the HTML. You could also set this in the WebPage's code-behind class.

<asp:datagrid id=dgExample AutoGenerateColumns="False" runat="server">
 <ALTERNATINGITEMSTYLE BackColor="LightSteelBlue">
 </ALTERNATINGITEMSTYLE>
 <headERSTYLE BackColor="RoyalBlue" HorizontalAlign="Center"></headERSTYLE>
 <COLUMNS>
   <asp:boundcolumn HeaderText="Name" DataField="Name"></asp:boundcolumn>
   <asp:boundcolumn HeaderText="Title" DataField="Title"></asp:boundcolumn>
   <asp:boundcolumn HeaderText="Phone" DataField="Phone"></asp:boundcolumn>
   <asp:boundcolumn HeaderText="Email" DataField="Email"></asp:boundcolumn>
   <asp:boundcolumn HeaderText="Salary" DataField="Salary"></asp:boundcolumn>
   <asp:boundcolumn HeaderText="SS#" DataField="SSNum"></asp:boundcolumn>
 </COLUMNS>
</asp:datagrid>

Complete Code-Behind Class

I am including the code for those of you who do not want to download the solution. This will provide you with a better understanding of the provided solution. Here are a few things to note:

The Populate DataGrid method utilizes the GetUsers method in the UsersFacade. This retrieves a collection of UserDTOs. In my example, I do not access a database, I just pre-populate the collection and return it. In a real application, this would access a database or an XML file.

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace DgColWebApp
{
    /// <summary>
    /// Summary description for DgColVisibility.
    /// </summary>
    public class DgColVisibility : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.Button btnUser;
        protected System.Web.UI.WebControls.DataGrid dgExample;
        protected System.Web.UI.WebControls.Button btnAdminView;
        protected System.Web.UI.WebControls.Label lblUiView;
        private UserFacade userFacade = new UserFacade();
        private enum UserView{User, Admin};
    
        private void Page_Load(object sender, System.EventArgs e)
        {
            if(!this.IsPostBack)
            {
                this.lblUiView.Text = UserView.User.ToString();
                this.PopulateGrid();
            }
        }

        private void PopulateGrid()
        {
            UserDTO[] users = userFacade.GetUsers();
            // Are there any users?            
            if(users == null)
            {
                return;
            }

            DataTable dt = new DataTable();
            //  Add the columns to the DataTable.
            dt.Columns.Add("Name");
            dt.Columns.Add("Title");
            dt.Columns.Add("Email"); 
            dt.Columns.Add("Phone");
            dt.Columns.Add("Salary");
            dt.Columns.Add("SsNum");
            // Loop through all of the users.
            foreach(UserDTO user in users)
            {
                // Generate the row.
                DataRow dr = dt.NewRow();
                // Add the data to the row.
                dr["Name"]        = user.Name;
                dr["Title"]        = user.Title;
                dr["Email"]        = user.Email;
                dr["Phone"]        = user.Phone;
                dr["Salary"]    = user.Salary;
                dr["SsNum"]        = user.SsNum;
                // Add the row to the datatable.
                dt.Rows.Add(dr);
            }
            
            // Bind the Data to the Grid.
            this.BindDataGrid(dt);
            this.HideShowColumns(this.dgExample);
        }

        /// <summary>
        /// This method Binds a DataTable to the example DataGrid.
        /// </summary>
        /// <PARAM name="dt"></PARAM>
        private void BindDataGrid(DataTable dt)
        {
            DataView dv = dt.DefaultView;

            // Bind the Data.
            this.dgExample.DataSource = dv;
            this.dgExample.DataBind();
        }

        private void HideShowColumns(DataGrid dg)
        {
            if(dg == null)
            {
                return;
            }
            
            // Loop through all of the columns in the grid.
            foreach(DataGridColumn col in dg.Columns)
            {
                // Are we in UserView Mode?
                if(this.lblUiView.Text == UserView.User.ToString())
                {
                    // Hide the Salary and SS# Columns.
                    if(col.HeaderText == "Salary" || col.HeaderText == "SS#")
                    {
                        col.Visible = false;
                    }
                }
                // Are we in AdminView Mode?
                else if(this.lblUiView.Text == UserView.Admin.ToString())
                {
                    // Show the Salary and SS# Columns.
                    if(col.HeaderText == "Salary" || col.HeaderText == "SS#")
                    {
                        col.Visible = true;
                    }
                }
            }
        }
        
        private void btnUser_Click(object sender, System.EventArgs e)
        {
            this.lblUiView.Text = UserView.User.ToString();
            this.PopulateGrid();
        }

        private void btnAdminView_Click(object sender, System.EventArgs e)
        {
            this.lblUiView.Text = UserView.Admin.ToString();
            this.PopulateGrid();
        }
    }
}

Screen Shots

Below is an example of the grid with alternate views. One view is the User View, which has a few columns hidden. The other view is the Admin View, which displays all columns.

User View (Columns Hidden)

User View

Admin View (All Columns Visible)

Admin View

Conclusion

The problem of referencing a column by index can become a nightmare. As you can see, there is a simple solution to this problem.

Note: This example will not work if you have AutoGenerateColumns = true;.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Kenny Young
United States United States
Member
Ken currently works as the Director of Software Engineering at the Pediatrics Epidemiology Center at the University of South Florida. He is involved in the architecture and design on numerous clinical trial projects. Some of the project include:
 
1. Rare Diseases Clinical Research Network
2. TrialNet - Diabetes
3. Teddy - Diabetes
4. CCOP - Cancer
5. AIDA - Diabetes

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberElham M31 Jan '13 - 0:19 
you saved my time a lot
thanks in advance
GeneralMy vote of 5membermanoj kumar choubey9 Feb '12 - 21:12 
Nice
GeneralGreat~!memberMetalzang5 Dec '08 - 2:34 
hi kenny... Laugh | :laugh:
 
good articles.
 
thanks for giving.
 
good bye ~
Questionhow to compare data in the cells in SQL with C#memberhamna130 Jun '08 - 3:12 
Can anyone tell me that how can i compare the data or text written in a table cell(in SQL) with the text written in a textbox in C#. I shall really be grateful if anyone can solve my problem.
Generallocalization header text problemmemberjsycsj21 Jan '08 - 16:13 
you know,now.most headertext should be localized.so hide column by header text isn't common use.do you have any other method?thanks
QuestionWhat if the column name is not in the datasetmemberGhalib Hamidi3 Oct '06 - 17:09 
Thanks for this article. It helped a lot.
In another situation, I want to hide a column, but the column is not in my dataset.
For example, in my code behind I have the following:
<asp:TemplateColumn HeaderStyle-BackColor="#9999ff" ItemStyle-Wrap="False" HeaderStyle-CssClass="vt"
SortExpression="m.Project_ID" HeaderText="Project_ID">

<asp:Label runat="server" Text='<%# Container.DataItem("Project_ID") %>' ID="TClblProject_ID">



But my sql does not contain Project_id. When I hide this column, the datagrid binding fails.
I also tried to delete the column, using delete method and it fails too. It complains that I have <%%> code in my column and can not be deleted.
 
Current solution I am using is to use a dummy column called Project_id and then hide it.
 
Any idea how I can make this work without the dummy column.
 
thanks
ghalib

GeneralHide Columns - Common Functionmembernandhucbm26 Jun '06 - 18:16 
Hi Kenny,
Thanks for giving idea.
From ur article i have enhanced your code here.
i am not familiar with c#.
 
My VB code here,
 

Private Sub HideColumns(ByVal dgr As DataGrid, ByVal columns As String, Optional ByVal Visible As Boolean = False)
With dgr
For Each col As DataGridColumn In .Columns
If InStr(columns, col.HeaderText) <> 0 Then
col.Visible = Visible
End If
Next
End With
End Sub
 
use this code
-------------
 

HideColumns(DgrPI,"Project Name,Board Name")
 

Sorry for poor english.

 

Regards,
 
Nanda kumar R.

GeneralProblems with datagrid.ColumnssussAnonymous15 Aug '05 - 20:55 
Hi
 
This looks like something I really need, but I have one problem.
 
When I copy/past this code into a test project, and try to compile, I get this error:
'System.Windows.Forms.DataGrid' does not contain a definition for 'Columns'
 
I have seen datagrid.Columns used a lot all over the web, but noone seems to have the same problem as I. I have also checked the msdn-library, but no Columns member found...
 
Is it just me? How can I make this work?
 
Thanks,
Sverre
GeneralRe: Problems with datagrid.ColumnsmemberKenny Young16 Aug '05 - 2:26 
As the article states, this is an example of an ASP.NET DataGrid. You are using the Windows Forms version of the DataGrid "System.Windows.Forms.DataGrid". You need to use the WebControl "System.Web.UI.WebControls.DataGrid" in an ASP.NET project, in order for this code to work.
 
Kenny
GeneralWhy didn't I think of this before...memberNiels Andersen25 Jul '05 - 20:04 
Thanks! Heck - should hove thought of the headers long ago - would have saved tons of dispare fiddling indexes - thanks again man.. life is better
GeneralRe: Why didn't I think of this before...memberKenny Young27 Jul '05 - 3:15 
Thanks for the comments Big Grin | :-D Glad the code could help.
 
Kenny
GeneralAutoGenerateColumns="True"memberccheee24 Jul '05 - 19:44 
Good Article..
 
What about get the headertext of the datagrid....
 
Is is possible to get all the columns when the Autogeneratecols in set to true and u populate the grid with a dataset?
 
Like
 
For each DataGridCOl as DatagridColumn in MyDgrd.columns
Response.write(DataGridCol.HeaderText)
Next
 
Cheers
C
GeneralRe: AutoGenerateColumns=&quot;True&quot;memberKenny Young25 Jul '05 - 8:39 
According to MSDN documentation, the DataGridColumnCollection is empty when AutoGenerateColumns = true. Only the columns explicitly added to the grid are added to the collection. Here is the MSDN article: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemwebuiwebcontrolsdatagridcolumncollectionclasstopic.asp[^]
 
Thanks,
 
Kenny
GeneralRe: AutoGenerateColumns=&quot;True&quot;memberccheee25 Jul '05 - 13:06 
Cheers
Makes sense
 
Chintan

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 20 Jul 2005
Article Copyright 2005 by Kenny Young
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid