Hiding Columns In A DataGrid
One of the frequently asked questions over at Asplists.com is: "How do I hide a column in a datagrid?". One very important point to note is that you cannot hide autogenerated columns in a data grid. The reason for this is that autogenerated columns are not added to the DataGrid's DataGridColumn collection. So, in order for a column to be hidden it must be either programmatically added to the DataGrid at runtime or explicitly defined (using templates) at design time with the AutoGenerateColumns property set to false (the code in this article will use this method).
This article provides sample code to hide a column (could easily be modified to hide more) for two different scenarios - hiding columns in response to an event on the page (common in web reports) or hiding columns to provide different functionality based on security levels.
First, let's look at how we can hide and show a column in a DataGrid in response to an event (the click of a button) on the page. You can see a live example here.
The code:
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<script runat="server">
Sub Page_Load(Sender As Object, E As EventArgs)
Dim myConnection As SqlConnection = new _
SqlConnection("Data Source=(local)\NetSDK; Trusted_Connection=Yes; Initial Catalog=pubs")
Dim myCommand As SqlCommand = New SqlCommand("Select * From Publishers", myConnection)
myConnection.Open()
myDataGrid.DataSource = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
myDataGrid.DataBind()
End Sub
Sub HideShow_Click(Sender As Object, E As EventArgs)
If myDataGrid.Columns(0).Visible = False Then
myDataGrid.Columns(0).Visible = True
Else
myDataGrid.Columns(0).Visible = False
End If
End Sub
</script>
<body>
<form runat="server">
<asp:DataGrid id="myDataGrid" Width="25%" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateColumn HeaderText="Publisher's ID">
<ItemTemplate>
<span><%# Container.DataItem("pub_id") %></span>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Publisher's Name">
<ItemTemplate>
<span><%# Container.DataItem("pub_name") %></span>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="City">
<ItemTemplate>
<span><%# Container.DataItem("city") %></span>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="State">
<ItemTemplate>
<span><%# Container.DataItem("state") %></span>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Country">
<ItemTemplate>
<span><%# Con