Hiding and Showing Columns in the DataGrid Control...
The DataGrid allows you to make columns visible or invisible on demand - even edit and other special columns. This article will show you how it is done.
Some developers have reported problems controlling the visibility of columns in the DataGrid control. The problem usually comes down to one fact. The DataGrid has a property called AutoGenerateColumns. The default value is "True". This means that when AutoGenerateColumns is set to True, the DataGrid will pull its column headings straight from the column names of the database table. If you allow this to happen you cannot control the visibility of the columns. You must use asp:BoundColumns and specify the HeaderText and Datafield properties in your DataGrid setup. This relatively simple change allows you accomplish the hiding and showing of columns as you wish. It also works with Edit and other special columns as you will see.
First, lets look at the html code in our .aspx page. Immediately below the <form> tag we have two buttons and set OnClick event handlers to two subroutines which will do the work of hiding and showing the appropriate columns in our code-behind file. In the DataGrid code, notice that AutoGenerateColumns is set to "False". Also notice that we have used asp:BoundColumns to set our HeaderText and DataFields. I have also set the Visible property to false so that nothing but the CompanyName column will be shown at startup. I have also added an Edit column although I did not wire it up to actually do any editing (the copy of the Customers table in the Northwind database I am using is readonly anyway). After the bound columns are some other datagrid properties just to make the grid look good.
|
<%@ Page Language="vb" Src="ShowHideCols.aspx.vb" Inherits="ShowHideCols" %> <!DOCTYPE html PUBLIC "-//W3C//DTD html 4.0 Transitional//EN"> <html> <head> <title>ShowHideCols</title> <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0"> <meta name="CODE_LANGUAGE" content="Visual Basic 7.0"> <meta name=vs_defaultClientScript content="JavaScript"> <meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5"> </head> <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server"> <asp:Button ID="btnShow" Text="Show Details" OnClick="ShowDetails" Runat="server" /> <asp:Button ID="btnHide" Text="Hide Details" OnClick="HideDetails" Runat="server" /> <p></p> <asp:DataGrid ID="dtgCusts" Runat="server" AutoGenerateColumns="False" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" BackColor="White" CellPadding="3" GridLines="Vertical"> <Columns> <asp:BoundColumn HeaderText="Company Name" DataField="CompanyName" /> <asp:BoundColumn HeaderText="Contact Name" DataField="ContactName" Visible="False" /> <asp:BoundColumn HeaderText="Contact Title" DataField="ContactTitle" Visible="False" /> <asp:BoundColumn HeaderText="City" DataField="City" Visible="False" /> <asp:BoundColumn HeaderText="Country" DataField="Country" Visible="False" /> <asp:BoundColumn HeaderText="Telephone" DataField="Phone" Visible="False" /> <asp:EditCommandColumn EditText="Edit" HeaderText="Edit" Visible="False" /> </Columns> <AlternatingItemStyle BackColor="#DCDCDC" /> <ItemStyle ForeColor="Black" BackColor="#EEEEEE" /> <headerStyle Font-Bold="True" ForeColor="White" BackColor="#000084" /> </asp:DataGrid> </form> </body> </html> |
Now for the code-behind file which is shown in two parts. The first part displayed below is just the usual page_load event which calls a "BindTheData" routine to actually get the data from the Customers table. All of this should be self explanatory.
|
Imports System.Data Imports System.Data.SqlClient Imports System.Configuration Public Class ShowHideCols : Inherits System.Web.UI.Page Protected btnShow As System.Web.UI.WebControls.Button Protected btnHide As System.Web.UI.WebControls.Button Protected dtgCusts As System.Web.UI.WebControls.DataGrid Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load If Not IsPostBack Then BindTheData End If End Sub Sub BindTheData Dim objConn As SqlConnection Dim objCmd As SqlCommand objConn = New SqlConnection(ConfigurationSettings.AppSettings("NorthwindConnection")) Dim strSql As String strSql = "SELECT Top 10 CompanyName, ContactName, ContactTitle, City, Country, Phone FROM Customers" objCmd = New SqlCommand(strSql, objConn) objConn.Open dtgCusts.DataSource = objCmd.ExecuteReader() dtgCusts.DataBind() objConn.Close() objConn.Dispose() End Sub |
Lastly comes our two subroutines to handle the showing and hiding of the columns in the grid other than Company Name. Since Company Name is Column(0), these routines use a simple For...Next loop to cycle through the remaining columns setting the visible property to true or false as appropriate.
|
Sub ShowDetails(sender As System.Object, e As System.EventArgs) Dim intCounter As Integer For intCounter = 1 to dtgCusts.Columns.Count - 1 dtgCusts.Columns(intCounter).Visible = True Next End Sub Sub HideDetails(sender As System.Object, e As System.EventArgs) Dim intCounter As Integer For intCounter = 1 to dtgCusts.Columns.Count - 1 dtgCusts.Columns(intCounter).Visible = False Next End Sub End Class |
There you have it. A simple way to control the visible property of your DataGrid columns.
You may download the code here.