Sacha Tomey's blog

Molding the Microsoft BI Stack

PartialCachingControl.CachedControl confusion

 
If you are using the @ OutputCache directive on a user control that you are adding programatically you will not receive a reference to the control type directly when you 'LoadControl'.  Instead you will be returned an object of type PartialCachingControl.
 
The CachedControl property is not hugely intuitive, it's actually set when the object is cached the first time - it's the property saying, "By the way, I've cached this object for you, just so you know".  If the object is already in the cache the CachedControl property returns null, this time it's saying, "I haven't had to cache anything as it was already in the cache".
 
If you do not add the PartialCachingControl to the control tree the CachedControl property will ALWAYS return null.
 
Here is a simple routine that demonstrates this:
 

void Page_Init()
{

Control Item;

Item = Page.LoadControl("test1.ascx");

Test1a.Controls.Add(Item);  // Comment this line to see the "always null" behavior.

if ( ((PartialCachingControl)Item).CachedControl != null)
{
      Response.Write("CachedControl is not null! - Control was not in the cache but is now ");

}
else
{
     Response.Write("CachedControl is null! - Control was already in the cache");

}

 

// To obtain a reference to your object access the control collection (Alternatively you can use 'FindControl')

MyUserControl myControl = (MyUserControl) Item.Controls[0];

}

 

Read the complete post at http://sachatomey.spaces.live.com/Blog/cns!6084F9B2487AF9A5!144.entry

Posted: Feb 09 2006, 11:20 AM by sachatomey
Filed under: