WebPart Properties

Webpart properties come in handy when you're creating webparts that need to store settings. Webpart properties are written the same as you would write a property in C# or VB .NET. However, you can also add a collection of attributes to make these properties visible to users. In this post, I'll continue to modify the helloWorld webpart that I've been using for these examples and I'll walk you through the most basic setup of a webpart property and explain what you can do with the attributes that I just mentioned.

The first thing you'll want to do is create an instance variable. You'll see that I created a private string variable in the first line of the following image. This variable will be used by the get/set of my property.

Next, I create a typical string property. Ignore the attributes and you'll see in the image that I have a public string called Text and it returns the value of the private variable and can assign a value to the variable.

Now we want to add the attributes. Before you can add the attributes, you'll need to add two using statements at the top of your class file if they aren't already there.
1. using System.Web.UI.WebControls.WebParts;
2. using System.ComponentModel;

You'll see 5 attributes in the code. The first 4 come from the first using statement. The Category attribute comes from the ComponentModel.



The 5 attributes and descriptions are:

Now we'll go to the CreateChildControls method and change one line. I highlighted the change in the next image. The line is a simple IF statement; if the property is null, the label will display "Hello World!", otherwise it will display whatever the property's value is.



Now, deploy the solution. Click the arrow in the webpart's Title bar and select "Modify Shared Web Part". The editorPart will open and at the bottom, you'll see that there is a new section called "Hello World Settings" which comes from the Category attribute. If you add another property and assign the same category, It will appear in the same section. You won't see two Hello World Settings sections. You'll then see a label with the text assigned in the WebDisplayName attribute. Finally, you'll see a textbox which appears by default because of the type of property. If you hover over "Label Text", you'll see the text from the WebDescription in a tooltip. If we had created a property from an enum, instead of getting a textbox, you would've seen a drop down list.

Time to wrap it up. Based on the code in the CreateChildControls method, if you leave the box blank, the webpart will display "Hello World!". I'm going to type "Hi Everyone" and click OK. The editorPart will hide itself and the label will now look like the following.



This was a really simple demonstration. Later, I'll show you how to create controls with custom code and display them in the editorPart.

Labels: