Monday, August 18, 2014

How to add a custom web part property to SharePoint

In the case where you need a web part to behave differently based on a variable set at the page level, the use of a custom web part property can come in handy. It allows you to change a custom setting at the web part level, which can then be used in the code to control the web part's behavior.

The following data types can be used as web part properties: string, bool, int, float, enum, System.DateTime, and System.Drawing.KnownColor and SharePoint will display the selection on the form in a relevant way (drop down box used for enum, etc.).

The folloiwng code example, should be added into the web part class (of type Microsoft.SharePoint.WebPartPages.WebPart). It creates a custom property called display, which is of type enum (custom enum called DisplayEnum). It has a default value, and can be accessed in the code via the "_display" variable.
private DisplayEnum _display = DisplayEnum.TitleAndBorder;
[WebBrowsable(true), Personalizable(PersonalizationScope.Shared)]
public DisplayEnum Display
      get { return _display; }
      set { _display = value; }
The property then appears under "miscellaneous" on the web part properties pop-up.

No comments:

Post a Comment