在DataList HeaderTemplate中查找控件

时间:2016-10-12 09:30:33

标签: asp.net vb.net datalist itemdatabound

问题

如何根据DataList的值更改DataItem标题模板中控件的值?

我无法更改ListItemType.HeaderItem中的值,因为在ListItem被绑定之前我也不知道设置它的值是什么。

ASP.NET

<asp:DataList ID="dl" runat="server" ShowHeader="true">
  <HeaderTemplate>
    <asp:Label ID="lbl" runat="server" Text="MyText" />
  </HeaderTemplate>
  <ItemTemplate>

  </ItemTemplate>
</asp:DataList>

代码背后

  Protected Sub dl_ItemDataBound(sender As Object, e As DataListItemEventArgs) Handles dl.ItemDataBound
    If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
      Dim Type As Integer = e.Item.DataItem("Type")

      If Type = 0 Then
        'Change lbl text in HeaderTemplate
      End If

    End If
  End Sub

2 个答案:

答案 0 :(得分:2)

使用以下代码:

  Private headerItem As DataListItem

  Protected Sub dl_ItemDataBound(sender As Object, e As DataListItemEventArgs) Handles dl.ItemDataBound

            If e.Item.ItemType = ListItemType.Header Then
                headerItem = e.Item
            End If
            If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
               Dim Type As Integer = e.Item.DataItem("Type")

               If Type = 0 Then
                    Dim lbl As Label = CType(headerItem.FindControl("lbl"), Label)
                    lbl.Text = "New Text"
               End If

            End If
  End Sub

答案 1 :(得分:1)

标题是其中一项,因此您需要遍历项目列表,找到标题,然后使用FindControl获取标签。但是,这里的问题是,在数据绑定过程的任何时候,您都无法确定标题项是否已绑定且标签是否存在。通常,您会发现它首先是数据绑定,但API中无法保证,因此您不应该依赖该行为。

所以你可以做的是有一些类字段来存储你需要的文本,然后在数据绑定已经发生时在PreRender上设置这个文本。类似的东西(C#,但应该很容易翻译成VB):

Private headerText as String

Protected Sub dl_ItemDataBound(sender As Object, e As DataListItemEventArgs) Handles dl.ItemDataBound
    If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
       Dim Type As Integer = e.Item.DataItem("Type")

       If Type = 0 Then
           headerText = "SomeText"
       End If

    End If
End Sub

Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
    Dim item As DataListItem
    For Each item In dl.items
        If item.ItemType = ListItemType.Header Then
            Dim HeaderLabel As Label = _
                CType(item.FindControl("lbl"), Label)
            HeaderLabel.Text = headerText
    End If
    Next item
End Sub