2

问题

如何根据 a 的值更改 a 的标头模板内的控件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
4

2 回答 2

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
于 2016-10-12T10:11:52.043 回答
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
于 2016-10-12T10:08:14.787 回答