I'm building a SP Web Part with custom properties which is working pretty much the way I want. One of these properties is a text field holding the name of a list in the SPWeb. I'd like to prevent the update of the property if the list is not present. Any suggestions how to cause the process to abort, and to display an error message (as we've seen with some OOTB web parts)?
1 Answer
You can do something like this:
string listName = null;
[WebBrowsable(true),
WebDisplayName("List Title"),
WebDescription(""),
Personalizable(PersonalizationScope.Shared),
Category("Custom Properties")]
public string listname {
get {
if (!string.IsNullOrEmpty(listName)) //needed first time you open the page to configure it since the list name SHOULD be filled.
return listName;
else
return "";
}
set {
if (!string.IsNullOrEmpty(value)){
SPWeb web = SPContext.Current.Web;
try
{
SPList list = web.Lists[value];
listName = value;
}
catch {
throw new Microsoft.SharePoint.WebPartPages.WebPartPageUserException("List was not found");
}
}
else
{
throw new Microsoft.SharePoint.WebPartPages.WebPartPageUserException("You provide a list title");
}
}
}
This code will check if the textbox is empty or not, if not, it will display an error message asking you to provide a list title, if it's filled, it will check if the list exists or not.
If you don't need the list title to be mandatory, remove the last "else" and exception.