摘要: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