For our e-office intranet I was working on a number of page layouts. In this page layout I wanted to use the out of the box Page Field Filter web part. After creating a new page using that page layout, the page crashed immediatly, showing the error message “An unexpected error has occurred”. After switching off customErrors in web.config, the error message was “The Hidden property cannot be set on Web Part ‘g_8271d6f6_a902_4fa4_88ce_ca9ae1b0d463′, since it is a standalone Web Part.”.
Context filter web parts are not visible at runtime, the only show up when the page is in edit mode. The web parts are using the hidden property to hide themselves. The way this is done does not work when using the web part directly in a page layout, resulting in this error message. I decided to change the Page Column Filter web part I released on CodePlex, to make this work.
In this web part I created a new override of the Hidden property. If there is a web part zone in which the web part is used, it behaves normally. If there is no web part zone, the property always returns false to prevent the web part from throwing the error message above. Here’s the code:
[Browsable(false)] public override bool Hidden { get { if (base.WebPartManager == null) { return base.Hidden; } if (this.Zone == null) { return false; } return !base.WebPartManager.DisplayMode.AllowPageDesign; } set { base.Hidden = value; } }
Because our web part now returns false when used in a page layout, we need another way to hide the web part at runtime. To do this I also created another override of the Visible property. Here is the code:
[Browsable(false)] public override bool Visible { get { if (base.WebPartManager == null) { return base.Visible; } if (this.Zone != null) { return true; } return base.WebPartManager.DisplayMode.AllowPageDesign; } set { base.Visible = value; } }
Please note that this code snippet always returns true if there is a web part zone. If you do not do this, your web part will throw an error when the web part is used in a web part zone (by adding it to the page through the web part gallery).
Now our context filter web part works as expected when used as a normal web part and when used in a page layout.