A Web part goes through different states when it gets added to a Web part page. When you first put a Web part on a SharePoint page, you’re typically in “design mode”, where you can modify the Web part properties. After you’re done editing, the SharePoint page and the Web part goes into “browse mode”. You can also preview the Web part in the site collection’s Web part gallery. And don’t forget, SharePoint Designer can also render the Web part in SP Designer’s page editor (Design window).
If you are developing Web parts, you will want to be able to check the state the Web part is in so that you can render content (controls and literals) appropriately. So, how do you check the different states of the Web part? You can check using the following:
(*Note: “this” that you see below is a reference to the Web part class. In other words, the expressions listed below are applicable only when inside the Web part class code.)
- WebPartManager.GetCurrentWebPartManager(this.Page).DisplayMode.Name – this property is a string with the following possible values:
- Catalog – this is the value of DisplayMode property when a user initiates the “edit page” command on a Web part page.
- Edit – this is the value of DisplayMode property when the user initiates modifying the Web part.
- Design – this is the value after the OK button is clicked on the Tool Pane (after editing the Web part properties in a Web part page).
- Browse – browsing the Web part in a normal fashion.
- this.DesignMode – the value is true when editing the Web part page containing the Web part is being edited in SharePoint Designer.
- this.IsStandalone – the value is true when the Web part is not contained in a Web part zone. This is typically true when you’re viewing the Web part in preview mode in the site collection Web part gallery.
- WebPartManager.GetCurrentWebPartManager(this.Page) – the object returned by this method will be null when the Web part is being previewed (in the site collection Web part gallery)
Checking the state of the Web part is useful when deciding what to render. For example, during regular browsing mode, the Web part will render the normal Web part contents. But if the Web part is being rendered in SharePoint Designer, you might want the Web part to render a “Preview command button” (the way invisble controls like the AJAX ScriptManager or ObjectDataSource look in layout/design editors).