Monday, August 04, 2008

Update ListItem Sharepoint programmatically

Hi,

How many time you try update a listitem and give a error like "Access Denied" or "Error Page", when you are working with event handlers or a simple postback, well the trick is using "AllowUnsafeUpdates"

SPSite site = SPControl.GetContextSite(Context);
SPWeb web = site.OpenWeb();

SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite csite = new SPSite(site.ID);
SPWeb cweb = csite.OpenWeb(web.ID);
csite.AllowUnsafeUpdates = true;
cweb.AllowUnsafeUpdates = true;
SPFile file = cweb.GetFile(this.fileURL.Value);
SPListItem itemH = file.Item;
itemH.Web.AllowUnsafeUpdates = true;
itemH.BreakRoleInheritance(true);
itemH.Web.AllowUnsafeUpdates = true;
itemH["Title"] = "My Name";
itemH.Update();
}

DONT FORGET TO DISPOSE
csite.Dispose();
cweb.Dispose();
Post a Comment