Custom Properties in SharePoint 2010 Webparts

This post aims to provide a glimpse into how Custom Properties can be utilised on SharePoint 2010 Custom Webparts. Indubitably Custom Properties are great way to facilitate extra functionality and build dynamic custom webparts that respond uniquely based on the value assigned to the custom properties.

Pre-requisite: I have used Visual Studio 2010, Visual Web Part Template to demonstrate a simple example.

Begin by creating a simple property in the WebPart.VB/CS file (just above the CreateChildControls() method call).


' Declare Custom Property

Dim _Flag As Boolean = Nothing

<Category("Configuration"), Description("Configure the custom property"), WebBrowsable(True), Personalizable(True), WebDisplayName("Set Flag Value")> _

Public Property CustomProperty() As Boolean

Get

Return _Flag

End Get

Set(ByVal value As Boolean)

_Flag = value

End Set

End Property

Now change the code in CreateChildControls() method


Protected Overrides Sub CreateChildControls()

'Dim control As Control = Page.LoadControl(_ascxPath)

'Controls.Add(control)


Dim control As MyWebPartUserControl = DirectCast(Page.LoadControl(_ascxPath), MyWebPartUserControl)

control.CustomProperty = CustomProperty

Controls.Add(control)

End Sub

Finally, in the WebPart.ascx.VB/CS, add the same property


Public Property CustomProperty() As Boolean

Get

Return _Flag

End Get

Set(ByVal value As Boolean)

_Flag = value

End Set

End Property

That’s it. Deploy the webpart and whilst you edit setting of the webpart you can set the property value as and when required. Furthermore, you can add logic for webpart to behave differently based on the value of the property set. What’s interesting is that Webpart Manager uses in built personalisation so while the Webpart has True for a user it can have False for other user. Brilliant.

Advertisements