Dynamically add columns to DataGrid

xiaoxiao2021-03-06  88

step:

1. Define Template Column

For example, we want to define a TemplateCoumn as follows:

PRIVATE _LBLDATEID AS STRING PUBLIC PUBLICTY LBLDATEID () AS STRING GET LBLDATEID = _lbldateid End Get Set (Byval Value As String) _lbldateID = VALUE End SET End Property

'Initialization effect: ID =' lblDate 'Runat = "server" Public Sub InstantiateIn (ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn' lblDate Dim lblDate As New Label lblDate.ID = LBLDATEID LBLDATE.Attributes.add ("Runat", "Server") AddHandler LBLDATE.DATABINDING, Addressof LBLDATE_DATABINDING Container.controls.add (LBLDATE)

End Sub

'Data Binding, Effect: Text =' <% # databinder.eval (Container, "DataItem.date")%> '

Private Sub LblDate_DataBinding (ByVal sender As Object, ByVal e As System.EventArgs) Dim lb As Label lb = CType (sender, Label) Dim container As DataGridItem container = CType (lb.NamingContainer, DataGridItem) lb.Text = DataBinder.Eval ( Container.DataItem, "Date") End Sub

END CLASS

2. Add your defined templateColumn to DataGrid, (generally written in Page_Load)

Dim col_date As TemplateColumn col_date = New TemplateColumn col_date.HeaderText = "Header Text" col_date.HeaderStyle.BackColor = Color.LightGreenDim item_date As rms.DataGridDateTemplate item_date = New DataGridDateTemplate item_date.lblDateID = "lblDate" col_date.ItemTemplate = item_date dgdMain.Columns. Add (col_date)

Note: The dynamic templateColumn must be added to each time PageLoad, that is, call the above code when postback.

3. Data binding, call the following code when you need to rebound data

DGDMain.DataSource = dgdmain.database ()

转载请注明原文地址:https://www.9cbs.com/read-106023.html

New Post(0)