Part four of my Web Part Properties series. Now it’s time for default values and what you should do when there are values that are incorrect or missing .
Last post discussed the .webpart file and I showed you how to do when setting up a Web Part in the Web Part Gallery with default values. Web Parts created using the SharePoint WebPart class can also define default values using the DefaultValue attribute, like this:
1: [...]
2: [DefaultValue("default value")]
3: public string Text {
4: get;
5: set;
6: }
As I prefer to use .NET 2.0 Web Parts I have to set my default values in the .webpart file, I also gain the benefit of not having the default values hard-coded.
Missing (default) values
To make the Web Part experience a whole lot better for your end users make sure that you always provide default value, so that the first thing they see is not an error message or an exception.
There are several cases when you can’t set a default value but instead want them to customize the Web Part. You should then provide an easy to understand instruction in your Web Part to tell the users to customize the Web Part.
I prefer to have a nice message and a hyperlink that the user can click which opens up the tool pane immediately like this:
Now all the user have to do is click the link and fill in the appropriate values.
The code for this simple Web Part looks like this:
1: protected override void CreateChildControls() {
2: if (string.IsNullOrEmpty(this.Text)) {
3: LiteralControl literalCtrl = new LiteralControl(
4: string.Format("<a id='MsoFrameworkToolpartDefmsg_{0}' href=\"javascript:MSOTlPn_ShowToolPane2Wrapper('Edit','129','{0}');\">Open the tool pane and enter a valid value.",
5: this.ID));
6: Controls.Add(literalCtrl);
7: }
8: else {
9: Label lblHello = new Label();
10: lblHello.Text = "Hello " + this.Text;
11: Controls.Add(lblHello);
12: }
13: }
This code creates a hyperlink which uses one of SharePoint’s built-in JavaScripts which opens the tool pane.
That’s all for today folks.