ASP.NET 2.0 - 如何以程控方式动态建立一个 GridView 控件
图表 1
有读者询问如何以程控方式替网页加入一个 GridView 控件。其实我们到目前为止并没有撰写 ASP.NET 2.0 的书籍,不过既然有读者问,我就试作了一个。图 1 所示之网页上的 GridView 控件就是完全以程序代码来动态建立。相关程序代码撰写于网页的 Load 事件处理例程中,摘要列示如下:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load
' 建立一个 ObjectDataSource 对象并设定其相关属性。
Dim os As ObjectDataSource = New ObjectDataSource()
os.ID = "DepartmentDtSource"
os.SelectMethod = "GetChartDataTable"
os.TypeName = "ChartSupplier"
' 建立一个 GridView 对象并设定其相关属性。
Dim gv As GridView = New GridView()
gv.ID = "PieChartGridView"
' 将 GridView 的数据来源设定成 ObjectDataSource 对象。
gv.DataSourceID = os.ID
gv.DataKeyNames = New String() {"部门"}
gv.AutoGenerateColumns = False
gv.AllowSorting = True
gv.AllowPaging = True
gv.PageSize = 2
' 建立一个 BoundField 数据行。
Dim myDepartmentField As BoundField = New BoundField()
myDepartmentField.HeaderText = "部门"
myDepartmentField.DataField = "部门"
' 建立一个 ImageField 数据行。
Dim myPieChartField As ImageField = New ImageField()
myPieChartField.HeaderText = "圆饼图"
myPieChartField.DataImageUrlField = "部门编码"
…
' 将自订的数据行加入 Columns 集合中。
gv.Columns.Add(myDepartmentField)
gv.Columns.Add(myPieChartField)
' 设定 GridView 对象的外观样式。
gv.BackColor = Color.FromName("#DEBA84")
gv.BorderColor = Color.FromName("#DEBA84")
gv.BorderStyle = BorderStyle.None
gv.BorderWidth = 1
gv.CellPadding = 3
gv.CellSpacing = 2
gv.FooterStyle.BackColor = Color.FromName("#F7DFB5")
gv.FooterStyle.ForeColor = Color.FromName("#
gv.RowStyle.BackColor = Color.FromName("#FFF7E7")
gv.RowStyle.ForeColor = Color.FromName("#
gv.SelectedRowStyle.BackColor = Color.FromName("#
gv.SelectedRowStyle.ForeColor = Color.White
gv.SelectedRowStyle.Font.Bold = True
gv.PagerStyle.ForeColor = Color.FromName("#
gv.PagerStyle.HorizontalAlign = HorizontalAlign.Center
gv.HeaderStyle.BackColor = Color.FromName("#A55129")
gv.HeaderStyle.ForeColor = Color.White
gv.HeaderStyle.Font.Bold = True
gv.PagerSettings.FirstPageImageUrl = "~/Images/First.gif"
gv.PagerSettings.LastPageImageUrl = "~/Images/Last.gif"
gv.PagerSettings.NextPageImageUrl = "~/Images/Next.gif"
gv.PagerSettings.PreviousPageImageUrl = "~/Images/Previous.gif"
gv.PagerSettings.Mode = PagerButtons.NextPreviousFirstLast
gv.PagerSettings.Position = PagerPosition.TopAndBottom
gv.PagerSettings.FirstPageText = "移到第一页"
gv.PagerSettings.LastPageText = "移到最后一页"
gv.PagerSettings.NextPageText = "移到下一页"
gv.PagerSettings.PreviousPageText = "移到前一页"
gv.PagerSettings.PageButtonCount = 4
' 将 ObjectDataSource 控件加入网页中。
Page.Form.Controls.Add(os)
' 将 GridView 控件加入网页中。
Page.Form.Controls.Add(gv)
gv.DataBind()
End Sub