Monday, February 09, 2009

Handy Hiding Panel

Often in SharePoint (Although this could be used elsewhere) I have a need to hide something from some users or in case of some situation. For instance I may want to hide a set of controls if the MOSS site is accessed from a specific URL (like the internet facing site).

In these cases I use a control I call the hiding panel. It is quite simple but so handy that I find it useful to blog about. The code first:

using System.Web.UI.WebControls;
using System.Web;
using System.Web.UI;

namespace JoeDemo
public abstract class HidingPanel : Panel
protected override void Render(System.Web.UI.HtmlTextWriter writer)
if (GetCondition())

protected abstract bool GetCondition();

[ToolboxData("<{0}: PublicUrlPanel runat=\"server\"></{0}: PublicUrlPanel>")]
public class PublicUrlPanel: HidingPanel
protected override bool GetCondition()
return HttpContext.Current.Request.Url.Host.ToLower() == "public";

I define an abstract class that is the generic hiding panel - it only renders when the condition is true. I then can have many classes that inherit from the Hiding panel, each implementing their own version of the GetCondition method.

The example here has the Public url panel which only displays if the host portion of the url is 'public'. Mind you this is not the best production code, the string shoudl not be baked in here but that's not the point here.

To use this, you simply add the panel to your page layout (or ASPX page if not in MOSS) and use the same way as a panel:

<myControls:PublicUrlPanel id="myPanel" runat="server">
<asp:Literal id="testLit" runat="server" Text="Accessed from public url"/>

Note that in SharePoint designer you should just be able to drag and drop this panel from the Server Controls list in the toolbox. If you are adding the code manually, you also need to register your assembly somewhere on the page with a register directive like

<%@ Register TagPrefix="myControls" Namespace="JoeDemo" Assembly="JoeDemo, Version=, Culture=neutral, PublicKeyToken=aaaaaaaaaa"%>

UPDATE: Today I was working with this code and realized that when the Panel renders, it can throw off the look of your web page due to its rendering of a DIV tag. To get around this, I simply stopped using a Panel control and switched to a PlaceHolder control. Cleaner rendering and no loss in functionality.

1 comment:

Andrew said...

I'm not going to lie; I read your code and it impressed me.
I've made the switch to C# and I like it. You sir, are still light years ahead of me though! you should be Mr. Masters in CS while I have a lowly B.Sc. But let's take this challenge to a bio lab or SQL server and see who wins then!! HAHA!

LOL! I'm all fired up from ranting about auto bailouts. *sigh* I wish Canada was more Euro and less Amero. :\