Saturday, June 04, 2011

SharePoint web parts properties validation

SharePoint web parts properties validation

Sometimes, in a custom web part we define the custom properties. It’s very difficult to validate properties every time by opening the web part in edit mode. So we needed to include validations on it so that whenever the user clicked OK or Apply the error message should be shown so that the correct input should be given.


Solution 1:

Earlier definition of the Property

private string _amitKumar=String.Empty;
public string AmitKumar
{
get {return _amitKumar;}
set {_amitKumar = value;}
}

Updated web part property definition,
private string _amitKumar =String.Empty;
public string AmitKumar
{
get {return _amitKumar;}
set
{
If(String.IsNullOrEmpty(value)
{
throw new Exception (“Value is required”);
}
else
_amitKumar =value;
}

}


The above approach works perfectly fine and will not let you close the properties pane until you provide the value in the _amitKumar field, you will keep getting exception for that web part. Now the disadvantage here is the user does not get a friendly message telling him what exactly is going wrong, though we specify the message in the new Exception constructor, it still shows a generic message.

Solution 2:

Now the above does fulfill the requirement but the client would clearly says they don’t like it because the error message does not talk about what happened and where, and hence there has to be a way to show the user our custom error message. So, we have used new exception of type WebPartPageUserException instead of Excepton. WebPartPageUserException class shows the exception custom message in the webpart property pane itself. So the correct or rather more appropriate way of implementing the above code would be,


private string _amitKumar =String.Empty;
public string AmitKumar
{
get {return _amitKumar;}
set
{
If(String.IsNullOrEmpty(value)
{
throw new WebPartPageUserException (“Value is required”);
}
else
_amitKumar =value;
}

}

And this will show the custom error message in the property pane so user knows what’s exactly is wrong.
Share:

0 comments:

About Me

My photo
Based in Bangalore, INDIA, Amit is a MCC. He has an MCA from the U.P.T.U., INDIA and holds Microsoft certifications including SharePoint 2007/2010/2013. He is an contributor to MSDN and http://amitkumarmca04.blogspot.com/. Amit have experience in SharePoint,ASP.Net with C#, Classic ASP, VB,Macros,HTML,JavaScript,JSON,BootStrap and AngularJS.

Followers

Labels