Click here to Skip to main content
15,885,278 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.
#Region "Directives"

Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Text

#End Region

Partial Public Class ShowHideGridViewColumnsClientVB
    Inherits System.Web.UI.Page

#Region "Properties & Fields"

    ''' <summary> 
    ''' List of column names 
    ''' </summary> 
    Private columnNames As List(Of String) = New List(Of String)(New String() _
        {"Id", "Description", "Assigned To", "Status"})

#End Region

#Region "Page Load"

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            _sampleData = Nothing

            ' Populate the GridView 
            Me.GridView1.DataSource = _sampleData
            Me.GridView1.DataBind()

            ' Setup the dropdown list to allow the user to show hidden columns 
            SetupShowHideColumns(Me.GridView1, Me.GridView1ShowHideColumns)
        End If
    End Sub

#End Region

#Region "GridView Events"

    Protected Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
        Dim gridView As GridView = DirectCast(sender, GridView)
        Dim sb As 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 Then
            ' Loop through each cell of the row 
            For columnIndex As Integer = 0 To e.Row.Cells.Count - 1
                ' 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 
                Dim hideLink As 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 Then
                    Dim columnTextLabel As New Label()
                    columnTextLabel.Text = e.Row.Cells(columnIndex).Text
                    e.Row.Cells(columnIndex).Controls.Add(columnTextLabel)
                End If
            Next
        End If

        ' Give each row an id 
        If e.Row.RowType = DataControlRowType.Pager Then
            e.Row.Attributes.Add("id", gridView.ClientID & "_pager")
        Else
            e.Row.Attributes.Add("id", (gridView.ClientID & "_r") + e.Row.RowIndex.ToString())
        End If
    End Sub

#End Region

#Region "Private Methods"

    ''' <summary> 
    ''' Method to build up the html for the dropdown list which 
    ''' will contain the names of the hidden columns. 
    ''' </summary> 
    ''' <param name="gridView">GridView control</param> 
    ''' <param name="showHideColumnsLiteral">Literal control to display client side show/hide columns dropdown</param> 
    Private Sub SetupShowHideColumns(ByVal gridView As GridView, ByVal showHideColumnsLiteral As Literal)
        Dim sb As 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()
    End Sub

#End Region

#Region "Sample Data"

    ''' <summary> 
    ''' Property to manage data 
    ''' </summary> 
    Private Property _sampleData() As DataTable
        Get
            Dim dt As DataTable = DirectCast(Session("TestData"), DataTable)

            If dt Is Nothing Then
                ' Create a DataTable and save it to session 
                dt = New DataTable()

                dt.Columns.Add(New DataColumn("Id", GetType(Integer)))
                dt.Columns.Add(New DataColumn("Description", GetType(String)))
                dt.Columns.Add(New DataColumn("AssignedTo", GetType(String)))
                dt.Columns.Add(New DataColumn("Status", GetType(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 
                Dim keys As DataColumn() = New DataColumn(0) {}
                keys(0) = dt.Columns("id")
                dt.PrimaryKey = keys

                _sampleData = dt
            End If

            Return dt
        End Get
        Set(ByVal value As DataTable)
            Session("TestData") = value
        End Set
    End Property

#End Region

End Class

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