繁体中文
设为首页
加入收藏
当前位置:.Net技术首页 >> Asp.Net开发 >> DPC:Hiding Columns In A DataGrid[等级:初 中]

DPC:Hiding Columns In A DataGrid[等级:初 中]

2007-08-15 08:00:00  作者:  来源:互联网  浏览次数:0  文字大小:【】【】【
简介: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 autoge...

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" %>

<%# Container.DataItem("pub_id") %>

<%# Container.DataItem("pub_name") %>

<%# Container.DataItem("city") %>

<%# Container.DataItem("state") %>

<%# Container.DataItem("country") %>

Next, let's look at how we can hide a column in a DataGrid based on the security level of the user. This example is not *actually* secure and security is not discussed in this article - we are trying to show how to hide DataGrid columns not how to secure a page! The code below checks a Querystring parameter called 'Security' each time the page loads. If 'Security' equals "Admin" then all of the columns are displayed. If 'Security' equals anything other than "Admin" then the first column in the DataGrid is hidden.

Click here to view the DataGrid with no priveleges. (No pub_id column)

Click here to view the DataGrid with Admin priveleges. (All columns visible)

The code:

<%@ Page Language="VB"%>

<%@ Import Namespace="System.Data" %>

<%@ Import Namespace="System.Data.SqlClient" %>

<%# Container.DataItem("pub_id") %>

<%# Container.DataItem("pub_name") %>

<%# Container.DataItem("city") %>

<%# Container.DataItem("state") %>

<%# Container.DataItem("country") %>

责任编辑:admin
相关文章