This post talks on how one can add custom properties to their SharePoint 2010 visual webparts. Microsoft has brought visual webparts for easing the developer life with SharePoint 2010 development. But when it comes to adding some custom properties for these webparts then there is bit of trouble hidden.
To troubleshoot this issue lets us dive in entities inside webpart project.
- Inside the webparts folder of the project one can see following files (considering webpart name as “VisualWebPart1”):
- Webpart class “VisualWebPart1.cs” that is derived from webpart class
- User control file “VisualWebPart1UserControl.ascx” and its associated designer and .cs files
Since we think that merely writing the property and setting its attributes to WebBrowsable=true & Personalizable inside the usercontrol class (VisualWebPart1UserControl.ascx.cs) file will go ahead and add properties into webpart, but in reality this will not work.
So how we gonna do this?
Even though the above assumption of ours is true but its partially true. The fact is, before adding this property to user control class we should
1. ONINIT EVENT:
Fires 1st: Startup of the Control and where in web parts, the storage system is loaded; also calls LoadViewState
(loads the view state for all controls); if you uncomment this event, you MUST include the base.OnInit(e) line.
This is the best place to define controls and its attributes that are added to the part. We can register
events of the controls here itself
2. ONLOAD EVENT:
Fires 2nd: OnLoad event – this is where startup functionality/processing happens, including trapping PostBack – AFTER THE
OnLoad events, any User Generated events (Click, and so on) are fired
3. CREATECHILDCONTROLS EVENT:
Fires 3rd (BEFORE any events and OnPreRender)- this creates any controls; you can use this event to do any
checking or resetting of controls. You can alternately define controls here (instead of OnInit) though
this can affect how well you can maintain view state.
4. Custom EVENT HANDLERS:
Fires 4th: Event Handlers – event handlers fire just AFTER CreateChildControls and before OnPreRender:
5. ONPRERENDER EVENT:
Fires 5th: OnPreRender event – called just before anything is drawn via the Render event
(here is where Properties can be changed before the controls are drawn); this event calls
SaveViewState to save the view state before rendering
6. RENDER EVENT:
Fires 6th (last): Render event – Render this control to the output (HTML Writer) parameter specified
The HTML writer to write out to