Click here to Skip to main content
15,884,176 members
Articles / Web Development / ASP.NET

Show / Hide GridView Columns in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.82/5 (17 votes)
12 Nov 2009CPOL4 min read 315.4K   5.1K   61  
Give users the ability to show or hide GridView columns as they require.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;

public partial class ShowHideGridViewColumnsServer : System.Web.UI.Page
{
    #region Properties & Fields

    /// <summary>
    /// List of column names
    /// </summary>
    List<string> columnNames = new List<string>() { "Id", "Description", "Assigned To", "Status" };

    private List<int> hiddenColumnIndexes
    {
        get
        {
            return ViewState["hiddenColumnIndexes"] == null ? new List<int>() : (List<int>)ViewState["hiddenColumnIndexes"];
        }
        set
        {
            ViewState["hiddenColumnIndexes"] = value;
        }
    }

    #endregion

    #region Page Load

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            _sampleData = null;

            // Populate the GridView
            this.GridView1.DataSource = _sampleData;
            this.GridView1.DataBind();

            hiddenColumnIndexes = new List<int>();
        }
    }

    #endregion

    #region Control Events

    protected void GridView1ShowHideColumns_SelectedIndexChanged(object sender, EventArgs e)
    {
        if(this.GridView1ShowHideColumns.SelectedIndex > 0)
        {
            int columnIndex = int.Parse(this.GridView1ShowHideColumns.SelectedValue);
            hiddenColumnIndexes.Remove(columnIndex);

            SetupShowHideColumns();
        }
    }

    #endregion

    #region GridView Events

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "hideCol")
        {
            // Add the column index to hide to the hiddenColumnIndexes list
            hiddenColumnIndexes.Add(int.Parse(e.CommandArgument.ToString()));
        }

        SetupShowHideColumns();
    }

    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;
    }

    #endregion

    #region Private Methods

    /// <summary>
    /// Setup the drop down list, adding options based on the hiddenColumnIndexes list 
    /// </summary>
    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;
        }

        // Populate the GridView
        this.GridView1.DataSource = _sampleData;
        this.GridView1.DataBind();
    }

    #endregion

    #region Sample Data

    /// <summary>
    /// Property to manage data
    /// </summary>
    private DataTable _sampleData
    {
        get
        {
            DataTable dt = (DataTable)Session["TestData"];

            if (dt == null)
            {
                // Create a DataTable and save it to session
                dt = new DataTable();

                dt.Columns.Add(new DataColumn("Id", typeof(int)));
                dt.Columns.Add(new DataColumn("Description", typeof(string)));
                dt.Columns.Add(new DataColumn("AssignedTo", typeof(string)));
                dt.Columns.Add(new DataColumn("Status", typeof(string)));

                dt.Rows.Add(new object[] { 1, "Create a new project", "John", "Complete" });
                dt.Rows.Add(new object[] { 2, "Build a demo applcation", "Helen", "In Progress" });
                dt.Rows.Add(new object[] { 3, "Test the demo applcation", "Peter", "Pending" });
                dt.Rows.Add(new object[] { 4, "Deploy the demo applcation", "Andy", "Pending" });
                dt.Rows.Add(new object[] { 5, "Support the demo applcation", "Claire", "Pending" });

                // Add the id column as a primary key
                DataColumn[] keys = new DataColumn[1];
                keys[0] = dt.Columns["id"];
                dt.PrimaryKey = keys;

                _sampleData = dt;
            }

            return dt;
        }
        set
        {
            Session["TestData"] = value;
        }
    }

    #endregion
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Chief Technology Officer
Ireland Ireland
I have been designing and developing business solutions for the aviation, financial services, healthcare 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