Obsidian Obsidian - 1 month ago 28
ASP.NET (C#) Question

Find control in DataList HeaderTemplate

QUESTION

How to change the value of a control inside the header template of a

DataList
based on the value of a
DataItem
?

I cannot change the value in
ListItemType.HeaderItem
because I do not know what value to set it too until the
ListItem
is bound.

ASP.NET

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

</ItemTemplate>
</asp:DataList>


CODE BEHIND

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

Answer

Use below code:

  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