显示和隐藏DataGrid中的列
作者:孟宪会 出自:【孟宪会之精彩世界】 发布日期:2003年5月4日 2点2分40秒
要显示和隐藏DataGrid中的列,最关键的是AutoGenerateColumns设置为False:下面就是实现这一功能的aspx代码和脚本代码:
ShowHideCols
后代码脚本
Imports System.Data
Imports System.Data.OleDb
Public Class ShowHideCols
Inherits System.Web.UI.Page
Protected WithEvents btnShow As System.Web.UI.WebControls.Button
Protected WithEvents btnHide As System.Web.UI.WebControls.Button
Protected WithEvents dtgCusts As System.Web.UI.WebControls.DataGrid
#Region " Web 窗体设计器生成的代码 "
'该调用是 Web 窗体设计器所必需的。
Private Sub InitializeComponent()
End Sub
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles MyBase.Init
'CODEGEN: 此方法调用是 Web 窗体设计器所必需的
'不要使用代码编辑器修改它。
InitializeComponent()
End Sub
#End Region
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles MyBase.Load
'在此处放置初始化页的用户代码
btnShow.Text = "显示列"
btnHide.Text = "隐藏列"
dtgCusts.Columns(1).HeaderText = ""
dtgCusts.Columns(0).HeaderText = "标题"
dtgCusts.Columns(2).HeaderText = "发布日期"
dtgCusts.Columns(3).HeaderText = "编辑"
If Not IsPostBack Then
BindTheData()
End If
End Sub
Sub BindTheData()
Dim objConn As OleDbConnection
Dim objCmd As OleDbCommand
objConn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
+ Server.MapPath("Test.mdb"))
Dim strSql As String
strSql = "SELECT Top 10 id,Title,CreateDate FROM Document"
objCmd = New OleDbCommand(strSql, objConn)
objConn.Open()
dtgCusts.DataSource = objCmd.ExecuteReader()
dtgCusts.DataBind()
objConn.Close()
objConn.Dispose()
End Sub
Sub ShowDetails(ByVal sender As System.Object, ByVal 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(ByVal sender As System.Object, ByVal 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