要動態產生datagrid 之columns 必須先建一個介面:
Public Class tempcheck
Implements ITemplate
Private plbnID As String
Public Sub New(ByVal lbnID As String)
plbnID = lbnID
End Sub
Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
Dim lbn As New CheckBox
lbn.ID = plbnID
lbn.Text = ""
lbn.Visible = True
AddHandler lbn.DataBinding, AddressOf TemplateControl_DataBinding
container.Controls.Add(lbn)
End Sub
Private Sub TemplateControl_DataBinding(ByVal sender As Object, ByVal e As System.EventArgs)
Dim lc As CheckBox
lc = CType(sender, CheckBox)
Dim container As DataGridItem
container = CType(lc.NamingContainer, DataGridItem)
lc.Checked = DataBinder.Eval(container.DataItem, plbnID)
End Sub
End Class
再datagrid Bind資料前定義column:
先將column資料讀入dataset: ds_bar
再分別新增datagrid : grdResults.Columns
及mytable.Columns
...
Dim myTable As DataTable = New DataTable
myTable.TableName = "auth"
myTable.Columns.Add(New DataColumn("my_sno", GetType(Integer)))
myTable.Columns.Add(New DataColumn("my_co", GetType(String)))
myTable.Columns.Add(New DataColumn("my_name", GetType(String)))
Dim v_bn As String
Dim i As Integer
Dim v_col As TemplateColumn
For i = 0 To ds_bar.Tables(0).Rows.Count - 1
v_col = New TemplateColumn
v_bn = ds_bar.Tables(0).Rows(i).Item("baritemname").ToString.Trim.Remove(0, 2)
v_col.HeaderText = v_bn
v_col.ItemTemplate = New tempcheck("my_bt_" + v_bn)
grdResults.Columns.Add(v_col)
myTable.Columns.Add(New DataColumn("my_bt_" + v_bn, GetType(Boolean)))
Next
......
最後再將myTable bind 到datagrid:
Dim dvwGrid As DataView = myTable.DefaultView
grdResults.DataSource = dvwGrid
Try
grdResults.DataBind()
Catch
grdResults.CurrentPageIndex = 0
grdResults.DataBind()
End Try
而資料的取得要用Request.Form:
For I = 0 To grdResults.Items.Count - 1
For jj = 0 To ds_bar.Tables(0).Rows.Count - 1
v_bn = ds_bar.Tables(0).Rows(jj).Item("baritemname").ToString.Trim.Remove(0, 2)
v_btn = "my_bt_" + v_bn
v_uid = grdResults.Items(I).UniqueID + ":"
v_chk = Request.Form(v_uid + v_btn)
.....