Tuesday, 12 November 2013

HOW TO ADD A CUSTOM VISUAL WEBPART PROPERTY IN SHAREPOINT 2010


I. INTRODUCTION
One of the requirements of my new webpart project is to allow the end user to customize some of its display parameters (E.g. warning messages, url links). We wanted to give our end-user the flexibility to change those data during runtime. Usually this is done by creating webpart properties.

II. REQUIREMENTS
- Sharepoint 2010

- Visual Studio 2010

III. IMPLEMENTATION

1. Create an empty sharepoint project in Visual Studio 2010. Add a Visual webpart to that sharepoint project. You will notice that Visual Studio creates several files to provision our new webpart.



2. Open the file named visualwebpart1.cs. You will notice that this class inherits from type Webpart. It has an override to the method CreateChildControls(). It also has a string path to the newly created UserControl.  What it does is just to load that usercontrol to the webpart. That usercontrol has a type ‘Control’ by default.



3. So on our example; we have already established that we have two important objects here. One is the webpart class itself, and the other one is the user control. Remember, we are only loading the user control (which serves as our UI) to our webpart class. 

Normally, the webpart property is done like the one below. We will add it on the visualwebpart1.cs file just after the CreateChildControls() method.




4. The next challenge here is that how are we going to relay this property so that our usercontrol will be able to read it. The solution is to create an instance of the webpart inside our usercontrol. 

Open VisualWebPart1UserControl.cs and add the following code just before the page load method.





5. Back in our VisualWebPart1.cs, remember that it is adding up our usercontrol with the type ‘Control’. Since we have added an instance of webpart on our usercontrol, we need to cast it with our own type of usercontrol which is ‘VisualWebPart1UserControl’.




6. So we can now access that property on our user control. So for example on a label control, we can now do something like this.

Assuming that we add a label control on our user control, we can now assign it a value using our newly created property. 




7. On your webpart toolbox, you can now see an available configuration for your property.


No comments:

Oscar L. Barit Jr. "I am Oca, i am writing to share with you some sharepoint matters that i learned on my day job. Enjoy! Mwah Mwah Tsup Tsup! "