Click here to Skip to main content
15,881,172 members
Articles / Web Development / ASP.NET
Article

Hide DataGrid Columns via HeaderText

Rate me:
Please Sign up or sign in to vote.
4.50/5 (19 votes)
20 Jul 20052 min read 212.2K   1.4K   63   15
Shows a developer how to dynamically hide or show DataGrid columns.

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.

C#
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".

C#
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.

HTML
<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.

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


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

Comments and Discussions

 
Questiongreat idea! Pin
Member 775742731-May-13 9:44
Member 775742731-May-13 9:44 
GeneralMy vote of 5 Pin
Elham M31-Jan-13 0:19
Elham M31-Jan-13 0:19 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey9-Feb-12 21:12
professionalManoj Kumar Choubey9-Feb-12 21:12 
GeneralGreat~! Pin
Metalzang5-Dec-08 2:34
Metalzang5-Dec-08 2:34 
Questionhow to compare data in the cells in SQL with C# Pin
hamna130-Jun-08 3:12
hamna130-Jun-08 3:12 
Generallocalization header text problem Pin
Lotto21-Jan-08 16:13
Lotto21-Jan-08 16:13 
QuestionWhat if the column name is not in the dataset Pin
Ghalib Hamidi3-Oct-06 17:09
Ghalib Hamidi3-Oct-06 17:09 
GeneralHide Columns - Common Function Pin
nandhucbm26-Jun-06 18:16
nandhucbm26-Jun-06 18:16 
GeneralProblems with datagrid.Columns Pin
Anonymous15-Aug-05 20:55
Anonymous15-Aug-05 20:55 
GeneralRe: Problems with datagrid.Columns Pin
Kenneth Young16-Aug-05 2:26
Kenneth Young16-Aug-05 2:26 
GeneralWhy didn't I think of this before... Pin
Niels Andersen25-Jul-05 20:04
Niels Andersen25-Jul-05 20:04 
GeneralRe: Why didn't I think of this before... Pin
Kenneth Young27-Jul-05 3:15
Kenneth Young27-Jul-05 3:15 
GeneralAutoGenerateColumns="True" Pin
ccheee24-Jul-05 19:44
ccheee24-Jul-05 19:44 
GeneralRe: AutoGenerateColumns=&quot;True&quot; Pin
Kenneth Young25-Jul-05 8:39
Kenneth Young25-Jul-05 8:39 
GeneralRe: AutoGenerateColumns=&quot;True&quot; Pin
ccheee25-Jul-05 13:06
ccheee25-Jul-05 13:06 
Cheers
Makes sense

Chintan

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.