Changing how a web part displays while in edit mode

There are a number of circumstances where you might want a web part to display differently depending upon the display mode of the page.

For example:

  • you might want to provide detailed instructions to the user while in edit mode (or connections mode, etc.);
  • the scriptaculous & prototype libraries conflict with Sharepoint javascript while in edit mode, causing a range of javascript errors;
  • you might want to provide a more rich user interface than Editor parts allow.

To do so, is quite simple in concept, just identify the display mode, and chuck an “if” statement in there. However, it did take me a while to find the right code and I thought it was worth posting about, especially because it can help you give users a more professional & polished interface.

First, where I looked for the display mode. There’s a WebPartManager class which exists, and has a display mode, but it’s tricky to find an instance.

If while inside CreateChildControls or OnPreRender you try:

WebPartDisplayMode currentMode = this.WebPartManager.DisplayMode;

you will get a null pointer exception, because this.WebPartManager == null. I don’t understand why, but it does.

What you need to do is execute the static GetCurrentWebPartManager function on your current page object (found this from a post by Rich from DevAndDesign.com).

WebPartManager wpm = WebPartManager.GetCurrentWebPartManager(this.Page);

if (!wpm.DisplayMode.AllowPageDesign)
{
this.Controls.Add(new Literal(“browse mode”));
}
else
{
this.Controls.Add(new Literal(“not browse mode”));
}

This relies on the boolean AllowPageDesign property. If true, the page is in edit mode (that includes the edit, connect, design & catalog modes). It’s definitely a bit silly that this.WebPartManager doesn’t work, especially because it’s such a simple property to implement. Maybe somebody can fill me in on the history?

Leave a Reply

Your email address will not be published. Required fields are marked *