How to access controls in HeaderTemplate and FooterTemplate
We are using ASP .NET, C# here in this example.
Lets take this repeater as an example.
<asp:Repeater ID="rpt" runat="server">
<HeaderTemplate>
<asp:CheckBox ID="chk1" runat="server" />
</HeaderTemplate>
<ItemTemplate>
HELLO
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chk2" runat="server" />
</FooterTemplate>
</asp:Repeater>
You can access the header and footer item controls on ItemCreated or even ItemDataBound. But not when you iterate through the repeater items like this:
foreach(RepeaterItem ri in rpt.Items)
{
if (ri.ItemType == ListItemType.Header)
{
CheckBox chk1 = (CheckBox)ri.FindControl("chk1");
chk1.Checked=true;
}
if (ri.ItemType == ListItemType.Footer)
{
CheckBox chk2 = (CheckBox)ri.FindControl("chk2");
chk2.Checked=true;
}
}
This will simply not work.
Without going through the explanation why it does not work, let see how we can get it work.
If you have a footer and header template defined in the repeater, header is item with index 0 and footer is the last item. Bearing that in mind, we can simply access the header and footer controls as follows:
CheckBox chk1 = (CheckBox)rpt.Controls[0].FindControl("chk1");
chk1.Checked = true;
CheckBox chk2 = (CheckBox)rpt.Controls[rpt.Controls.Count - 1].FindControl("chk2");
chk2.Checked = true;
Currently rated 5.0 by 1 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5