Access HeaderTemplate and FooterTemplate Controls

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;

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by: WebCosmo
Posted on: 7/17/2008 at 11:08 AM
Categories: Programming / Coding
E-mail |  Stumble it! |  Propeller it! |  Digg it! |  del.icio.us |  Technorati
Post Information: Permalink | Comments (1) | Post RSSRSS comment feed

Related posts

Comments

Yiwu us

Monday, July 28, 2008 4:21 PM

Yiwu

so good codes.. thanks

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

Wednesday, August 27, 2008 4:59 PM