When we are trying to update values of list default columns like created by, modified by programmatically it throws an error saying “The field you are trying to update may be read only” .However we can set the values of these Read Only columns by using their Internal Name (For more info on Internal,External names of a field refer
here)
Let us assume that I need to update 2 such column namely “Created By” and “Modified By” then code can be like
using (SPSite site = new SPSite(SPContext.Current.Site.ID))
{
using (SPWeb web = site.OpenWeb())
{
site.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = true;
// Access the List
SPList list = web.Lists["Your_List_Name"];
// Access the item for which you want to update values
SPListItem listItem = list.Items[6];// choose the index corresponding to item
// Set the value for Created By field
listItem["Author"] = SPContext.Current.Web.CurrentUser;
// Set the value for Modified By field
listItem["Editor"] = SPContext.Current.Web.CurrentUser;
listItem.Update();
web.Update();
}
}
Like this we can programmatically set value of any field through its internal name.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment