CSDN博客

img kongdir

动态向Datagrid中添加列

发表于2004/10/15 11:42:00  478人阅读

分类: ASP.NET

步骤:
    一.定义Template Column
        比如我们要定义一个如下的TemplateCoumn:
<asp:TemplateColumn>
   <ItemTemplate>
       <asp:Label ID='lblDate' Runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.date") %>'>
       </asp:Label>
   </ItemTemplate>
</asp:TemplateColumn>
        则应当定义一个类DataGridDateTemplate,代码如下:
                          Public Class DataGridDateTemplate
    Implements ITemplate
 
    'Label 的ID
    Private _lblDateID As String
    Public Property lblDateID() As String
        Get
            lblDateID = _lblDateID
        End Get
        Set(ByVal Value As String)
            _lblDateID = Value
        End Set
    End Property
 
   '初始化,效果: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
 
    '数据绑定,效果: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

    .向Datagrid中添加自己定义的TemplateColumn,(一般在Page_Load中写)

        Dim col_date As TemplateColumn
        col_date = New TemplateColumn

        col_date.HeaderText = "Header Text"
        col_date.HeaderStyle.BackColor = Color.LightGreen

        Dim item_date As rms.DataGridDateTemplate
        item_date = New DataGridDateTemplate
        item_date.lblDateID = "lblDate"
        col_date.ItemTemplate = item_date
        dgdMain.Columns.Add(col_date)

            注意:必须在每次PageLoad的时候添加动态的TemplateColumn,即在Postback的时候也要调用上面的代码。

     三.数据绑定,在需要重新绑定数据的时候调用以下代码

        dgdMain.DataSource = <data source>
        dgdMain.DataBind()

阅读全文
0 0

相关文章推荐

img
取 消
img