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

Show / Hide GridView Columns in ASP.NET

, 12 Nov 2009
Rate this:
Please Sign up or sign in to vote.
Give users the ability to show or hide GridView columns as they require.

Introduction

This article demonstrates how to give users the ability to show or hide GridView columns as they require. This can be useful if there are some columns in a GridView which are not always required by all users; these could be hidden by default, and easily made visible by the users who require them. Rather than display a large GridView which goes off the screen, you can have a neat GridView which still has all of the required columns. It is also a useful technique for a report type page where users have the flexibility to choose which GridView columns are printed.

Background

The RowCreated and ItemDataBound events allow you to inject HTML, CSS, and JavaScript to enhance the GridView control in any number of ways. These two articles also use similar principals:

The Sample Application

In the sample Task Management application, it may not always be necessary to display the task "Id" column, or when printing a Task report, a user may not want to print the "Assigned To" column.

Here is a basic GridView showing four columns:

Screenshot - Show Hide GridView Columns

By clicking on the minus symbol in a column header, a user can hide a column; in this case, the "Id" column is hidden:

Screenshot - Show Hide GridView Columns

A hidden column can be made visible again by selecting the column name from the "Show Column" drop down list, which appears when the first column is hidden.

Here is a Print Preview of the same page with the Id column hidden:

Screenshot - Show Hide GridView Columns

This article will demonstrate two methods of showing and hiding GridView columns, one on the client side and one on the server side.

Show / Hide GridView Columns on the Client Side

Most of the code for generating the client side functionality is in the GridView's RowCreated event. When the GridView header row is created, a HyperLink control with a minus symbol is inserted into each header cell for hiding that column. The hyperlink will call a JavaScript method called HideCol from its onclick event. A CSS class is also applied to increase the size of the minus symbol. As each DataRow is being created, an Id is added to each row so that it can be identified by the JavaScript.

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    GridView gridView = (GridView)sender;
    StringBuilder sb = new StringBuilder();

    // For the header row add a link to each header
    // cell which can call the HideCol javascript method
    if (e.Row.RowType == DataControlRowType.Header)
    {
        // Loop through each cell of the row
        for (int columnIndex = 0; columnIndex < e.Row.Cells.Count; columnIndex++)
        {
            // Build the hide column link
            sb.Remove(0, sb.Length); // first empty the StringBuilder
            sb.Append("javascript:HideCol('");
            sb.Append(gridView.ClientID);
            sb.Append("', ");
            sb.Append(columnIndex);
            sb.Append(", '");
            sb.Append(columnNames[columnIndex]);
            sb.Append("');");

            // Build the "Hide Column" HyperLink control
            HyperLink hideLink = new HyperLink();
            hideLink.Text = "-";
            hideLink.CssClass = "gvHideColLink";
            hideLink.NavigateUrl = sb.ToString();
            hideLink.Attributes.Add("title", "Hide Column");

            // Add the "Hide Column" HyperLink to the header cell
            e.Row.Cells[columnIndex].Controls.AddAt(0, hideLink);

            // If there is column header text then
            // add it back to the header cell as a label
            if (e.Row.Cells[columnIndex].Text.Length > 0)
            {
                Label columnTextLabel = new Label();
                columnTextLabel.Text = e.Row.Cells[columnIndex].Text;
                e.Row.Cells[columnIndex].Controls.Add(columnTextLabel);
            }
        }
    }

    // Give each row an id
    if (e.Row.RowType == DataControlRowType.Pager)
        e.Row.Attributes.Add("id", gridView.ClientID + "_pager");
    else
        e.Row.Attributes.Add("id", gridView.ClientID + "_r" + e.Row.RowIndex.ToString());
}

The HTML for the "Show Columns" drop down list is generated in the SetupShowHideColumns method and written out to a Literal control.

private void SetupShowHideColumns(GridView gridView, Literal showHideColumnsLiteral)
{
    StringBuilder sb = new StringBuilder();

    sb.Append("<div class=\"showHideColumnsContainer\">");
    sb.Append("<select id=\"");
    sb.Append(gridView.ClientID);
    sb.Append("_showCols\" onchange=\"javascript:ShowCol('");
    sb.Append(gridView.ClientID);
    sb.Append("', this.value);\" style=\"display:none;\">");
    sb.Append("<option>- Show Column -</option></select></div>");

    showHideColumnsLiteral.Text = sb.ToString();
}

After the data has been bound to the GridView, the remainder of the work is done by the JavaScript in the ShowHideColumns.js file. When a hyperlink in a column header is clicked, it passes the GridView name, column index, and column name to the HideCol JavaScript method which can then find each table cell in that column. The style of each cell is modified by adding a display:none; style to the cell, hiding the column.

When an option is selected from the "Show Column" drop down list, the ShowCol JavaScript method is called, which removes the display:none; style from each cell in the column, displaying it again.

Show / Hide GridView Columns on the Server Side

The server side example also uses the RowCreated event to add a minus symbol to the column headers, this time as a LinkButton control. The CommandName and CommandArgument properties are setup so that when the LinkButton raises the RowCommand event, the associated column can be hidden. Previously hidden column indexes are stored in a List<int>, and these columns are hidden as the row is being created.

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    // For the header row add a link button to each header
    // cell which can execute a row command
    if (e.Row.RowType == DataControlRowType.Header)
    {
        // Loop through each cell of the header row
        for (int columnIndex = 0; columnIndex < e.Row.Cells.Count; columnIndex++)
        {
            LinkButton hideLink = new LinkButton();
            hideLink.CommandName = "hideCol";
            hideLink.CommandArgument = columnIndex.ToString();
            hideLink.Text = "-";
            hideLink.CssClass = "gvHideColLink";
            hideLink.Attributes.Add("title", "Hide Column");

            // Add the "Hide Column" LinkButton to the header cell
            e.Row.Cells[columnIndex].Controls.AddAt(0, hideLink);

            // If there is column header text then
            // add it back to the header cell as a label
            if (e.Row.Cells[columnIndex].Text.Length > 0)
            {
                Label columnTextLabel = new Label();
                columnTextLabel.Text = e.Row.Cells[columnIndex].Text;
                e.Row.Cells[columnIndex].Controls.Add(columnTextLabel);
            }
        }
    }

    // Hide the column indexes which have been stored in hiddenColumnIndexes
    foreach(int columnIndex in hiddenColumnIndexes)
        if (columnIndex < e.Row.Cells.Count)
            e.Row.Cells[columnIndex].Visible = false;
}

The "Show Columns" drop down list is setup in the SetupShowHideColumns method. Previously hidden column names are added to the options.

private void SetupShowHideColumns()
{
    this.GridView1ShowHideColumns.Items.Clear();

    if (hiddenColumnIndexes.Count > 0)
    {
        this.GridView1ShowHideColumns.Visible = true;
        this.GridView1ShowHideColumns.Items.Add(new ListItem("-Show Column-", "-1"));
        
        foreach (int i in hiddenColumnIndexes)
            this.GridView1ShowHideColumns.Items.Add(
                    new ListItem(columnNames[i], i.ToString()));
    }
    else
    {
        this.GridView1ShowHideColumns.Visible = false;
    }
}

Examples in the Demo Project

Client-side examples:

  • C#.NET - Client-side example accessing data stored in session.
  • C#.NET - Client-side example which includes: MasterPage, UpdatePanel, GridView editing, paging and sorting, accessing data via the SqlDataSource control.
  • VB.NET - Client-side example accessing data stored in session.

Server-side examples:

  • C#.NET - Server-side example accessing data stored in session.
  • C#.NET - Server-side example which includes: MasterPage, UpdatePanel, GridView editing, paging and sorting, accessing data via the SqlDataSource control.
  • VB.NET - Server-side example accessing data stored in session.

Conclusion

If you want to give your users the ability to show and hide GridView columns in ASP.NET, then this technique may be useful.

History

  • v1.0 - 12th Nov. 2009.

License

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

About the Author

Declan Bright
Architect
Ireland Ireland
I have been designing and developing business solutions for the aviation and telecommunications industries since 1999. My experience covers a wide range of technologies and I have delivered a variety of web and mobile based solutions.

Comments and Discussions

 
GeneralMy vote of 4 Pinmemberchirag4818-Jun-13 20:39 
QuestionCompatible with paging? Pinmembernathan_wilson20-Aug-12 12:01 
QuestionQuery Related To hide gridview column PinmemberJeeten Parmar22-Dec-11 19:36 
GeneralMy vote of 5 PinmemberMadhavJoshi26-Sep-11 3:57 
GeneralThanks Lots for this PinmemberMadhavJoshi26-Sep-11 3:56 
GeneralHide column with checkboxlist Pinmemberamolpandit22-Dec-09 21:51 
GeneralThanx Declan Pinmemberamolpandit22-Dec-09 21:48 
GeneralYou got one vote for "Best VB.NET article of November 2009" PinmemberMarcelo Ricardo de Oliveira11-Dec-09 23:39 
GeneralGood article PinmemberGeosynch5-Dec-09 10:17 
GeneralRe: Good article PinmemberDeclan Bright6-Dec-09 23:12 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 12 Nov 2009
Article Copyright 2009 by Declan Bright
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid