如何动态生成DataGrid的列?

如何动态生成DataGrid的列?

Public mygrid As New DataGrid
Public SortExpression As String
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
If Not IsPostBack Then
Me.Controls.Add(MakeGrid())
End If


End Sub
Function MakeGrid() As DataGrid
mygrid.CellPadding = 2
mygrid.Attributes.Add("align", "center")
mygrid.CellSpacing = 0
mygrid.Width = Unit.Pixel(500)
mygrid.BorderWidth = Unit.Pixel(1)
mygrid.BorderColor = ColorTranslator.FromHtml("Black")
mygrid.AutoGenerateColumns = False
mygrid.ForeColor = ColorTranslator.FromHtml("Black")
'mygrid.Font.Size =
mygrid.Font.Name = "ËÎÌå"
mygrid.AllowSorting = True

 

'mygrid.SortCommand = new DataGridSortCommandEventHandler(Sort_Grid);


mygrid.HeaderStyle.BackColor = ColorTranslator.FromHtml("Gold")
mygrid.HeaderStyle.ForeColor = ColorTranslator.FromHtml("Black")
mygrid.HeaderStyle.Font.Name = "ËÎÌå"
'mygrid.HeaderStyle.Font.Size = 9
mygrid.HeaderStyle.Font.Bold = True
mygrid.HeaderStyle.HorizontalAlign = HorizontalAlign.Center


mygrid.AlternatingItemStyle.BackColor = ColorTranslator.FromHtml("Silver")
mygrid.AlternatingItemStyle.ForeColor = ColorTranslator.FromHtml("Black")
mygrid.ItemStyle.HorizontalAlign = HorizontalAlign.Left
Dim FirstName As New BoundColumn
FirstName.HeaderText = "ID"
FirstName.DataField = "ID"
mygrid.Columns.AddAt(0, FirstName)

Dim Pid As New BoundColumn
Pid.HeaderText = "ParentID"
Pid.DataField = "ParentID"
mygrid.Columns.AddAt(1, Pid)
'mygrid.Columns.AddAt(2, newC())
Dim d As New Data

mygrid.DataSource = d.getTable
mygrid.DataBind()
Return mygrid
End Function
Function newC() As DataGridColumn
Dim text As New BoundColumn
text.HeaderText = "Context"
text.DataField = "context"
Return text

End Function

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Controls.Add(MakeGrid())
Dim text As New BoundColumn
text.HeaderText = "Context"
text.DataField = "context"
mygrid.Columns.AddAt(2, text)
Dim d As New Data
mygrid.DataSource = d.getTable
mygrid.DataBind()
End Sub