Home » Programming / Coding

Access HeaderTemplate and FooterTemplate Controls in ASP .NET

17 July 2008 738 views No Comment

How to access controls inĀ  HeaderTemplate and FooterTemplate in ASP .NET

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;

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.