ARTICLES

Home  > Articles  >  Custom SharePoint webpart property error messages
Custom SharePoint webpart property error messages
by Yaroslav Pentsarskyy

 You could have displayed error message as a custom label, but then your properties would be saved in SharePoint database and there is no guarantee that those values entered by the user will not result in generic SharePoint error message that nobody wants to see. 

Displaying important errors right in the tool pane of the webpart properties - is a standard and clean approach that most of the commercial products use.

The best approach in this case is to set a handler on your SET public property to validate the value the user is tring to enter and return an error or persist the value.

Something like this (where I validate email address with my ValidEmail custom function):

string formRecipient;
        [
            Personalizable(PersonalizationScope.Shared),
            WebBrowsable(true),
            WebDisplayName("Form Recipient Email"),
            WebDescription("Email address of the complaint administrator")
        ]
        public string FormRecipient
        {
            get { return formRecipient; }
            set
            {
                if (!ValidEmail(value))
                {
                    throw new WebPartPageUserException(”Invalid ‘Form Recipient’ email address. Only one valid email address permitted by the system.”);
                }
                else
                {
                    formRecipient = value;
                }
            }
        }

In here WebPartPageUserException  will ensure your exception message is displayed on the top of the webpart tool pane and properties are not saved.

SharePoint will know how to properly interpret the exception and bubble it up to the user interface to render a warning label and prevent save.

Cheers!

Yaroslav Pentsarskyy, SharePoint MVP
Blog: www.sharemuch.com