Posts Tagged ‘SPItemEventReceiver’
Posted on October 19, 2009 - by Rouslan Grabar
How to allow only Folder items to be created in the List root folder
Sometimes you need to prohibit creation of list items in the root folder of the list. For example, you invented some pretty looking, folder-based, issue cataloguing system, but end users create issues in list’s root folder no matter how hard you beg them not to.
Below you will find the code that looks into HttpContext for a “RootFolder” and “Type” parameters and makes use of SPItemEventProperties.Cancel property.
public class IssueItemEventReceiver : SPItemEventReceiver
{
private HttpContext _current;
public IssueItemEventReceiver()
{
_current = HttpContext.Current;
}
public override void ItemAdding(SPItemEventProperties properties)
{
using (SPSite site = new SPSite(properties.SiteId))
{
using (SPWeb web = site.OpenWeb(properties.RelativeWebUrl))
{
SPList list = web.Lists["Issues"];
string rootRelUrl = string.Format("{0}/{1}",
properties.RelativeWebUrl,
list.RootFolder);
bool isFolder = (_current.Request.Params["Type"] != null
&& _current.Request.Params["Type"] == "1");
bool isInRoot = (_current.Request.Params["RootFolder"] == rootRelUrl);
properties.Cancel = !(isFolder && isInRoot);
//// here you can redirect to your very own page in _layouts folder
//if (properties.Cancel)
//{
// SPUtility.Redirect("myFeatureFolderInLayoutsFolder/MyCustomErrorPage.aspx",
// SPRedirectFlags.RelativeToLayoutsPage | SPRedirectFlags.Trusted,
// _current);
//}
}
}
}
}

