Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Wednesday, November 30, 2011

Validating WebPart Properties

Nothing is more annoying than configuring a web part by changing its properties and then hitting ok only to see the web part display an error that a property is invalid - and having to open the properties pane again to fix the problem.
To avoid this, best practice is to validate the data entered in the "set" of the web part property. For example, if I have a web part property that needs a comma delimited array of numbers (for example 1,2,3,4) and I don't want to build a tool part just for that, I can still build a property like this:
public string NumberArray
{
    get{return _numberArray;}
    set{_numberArray=value;}
}
The problem with the code above is that it is not validating that the string entered is indeed an array of numbers. To do that, I could change the code to something more like this:
public string NumberArray
{
    get{return _numberArray;}
    set{
          string [] arr = value.split(',');
          foreach (string item in arr)

          {
             int i;
             if(!int.TryParse(item,out i))
                throw new Exception("The item \""+item+"\" is not a valid number");
          }

_numberArray=value;}

}
This will do what I want - preven the user from closing the web part properties pane before fixing the error in the property, but it will not display the nice informative error to the user. Instead, it will show a generic error "An error has occurred" despite the fact that I specified what the error was when I threw the error!
Why? because to do that the exception must be of type WebPartPageUserException.
So the correct code for validating my sample property would be:
public string NumberArray
{
    get{return _numberArray;}
    set{
          string [] arr = value.split(',');
          foreach (string item in arr)
          {

             int i;
             if(!int.TryParse(item,out i))
                throw new WebPartPageUserException("The item \""+item+"\" is not a valid number");
          }


_numberArray=value;}
}

Now - when the users put an invalid value in my property they will be notified that it is invalid, and which value it was.

No comments:

Post a Comment