How to address control within templated custom control from code behind

How to address control within templated custom control from code behind

Post by Earl Teigr » Thu, 10 Jun 2004 01:30:08



I have created a simple custom control that uses a table to create space
around its contents. The code in the aspx page is show below. My problem is
that the controls within the template can not be directly accessed from the
code behind. In the code listing below, trying to use "Literal1" control in
the code behind results in a null reference exception. How do I make the
controls within my templated custom control accessible in the code behind?

Thanks

Earl

<cc1:SpacerControl id="SpacerControl1" SpaceAbove="3" SpaceBelow="3"
SpaceRight="100" SpaceLeft="100" WidthInPercent="false" FrameColor="blue"
TableAlign="Center" ContentsWidth="500px" TotalWidth="75%" runat="server">
<ITEMTEMPLATE>
Some Text
<asp:Literal id="Literal1" runat="server"></asp:Literal>
</ITEMTEMPLATE>
</cc1:SpacerControl>
 
 
 

How to address control within templated custom control from code behind

Post by Rateru » Thu, 10 Jun 2004 03:27:04

You'll have to cast the specific reference to the control in your controls "controls" collection

dim lit as literal
lit = DirectCast(mySpacerControl.Controls(1), Literal) <-- Something like that anyway, getting the appropriate index is the tricky part.

 
 
 

How to address control within templated custom control from code behind

Post by Earl Teigr » Thu, 10 Jun 2004 04:18:39

Raterus,

Thank you, I got it. Though I had trouble finding the correct index value, I
used the handy "FindControl" method and it worked perfectly! Code looks like
this (in C#)
Literal Literal1 = (Literal)SpacerControl1.FindControl("Literal1");

One more obstacle overcome!

Earl





You'll have to cast the specific reference to the control in your controls
"controls" collection

dim lit as literal
lit = DirectCast(mySpacerControl.Controls(1), Literal) <-- Something like
that anyway, getting the appropriate index is the tricky part.




is
the
in