views:

41

answers:

3

I have a control that can be placed in a Web form (.aspx) or a Master Page (.master). I want it to function differently depending on which one it's in.

My first thought is to climb the control tree back to the root and see if I cross over a MasterPage control. If so, then it would have to be in the Master Page.

But, this seems inefficient. Is there a better way?

A: 

I am not sure if there is a more efficient way, but if you are climbing up the hierarchy, do so through NamingContainer. You will skip plenty of unnecessary hops by using that.

Unless is a control that will appear lots of time on the page, going through the NamingContainer will be more than enough :)

eglasius
A: 

Your control should have a property for changing behavior and you should set that property differently in your master/form.

ssg
what if the control is inside an user control ;)
eglasius
It becomes a bad design.
ssg
A: 

First check if the page has a master page at all. Then go through the control tree to look for a content place holder:

public static bool IsInMaster(Control control) {
 if (control.Page.Master == null) return false;
 while (control != null) {
  if (control is ContentPlaceHolder) return false;
  control = control.Parent;
 }
 return true;
}
Guffa
Excellent solution. Thanks.
Deane