I have tried this code snippet (from console application):
using(SPSite site = new SPSite("http://mycoolsite"))
{
using(SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["My List"];
SPField fldTitle = list.Fields["Title"];
fldTitle.Required = false;
fldTitle.Title = "New title";
fldTitle.Update();
}
}
and it works.
Edited:
After reading comments I have changed code to FeatureActivated event:
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb web;
SPSite site;
//Parent can be site or web depending on feature scope
object oParent = properties.Feature.Parent;
if (properties.Feature.Parent is SPWeb)
{
web = (SPWeb)oParent;
site = web.Site;
}
else
{
site = (SPSite)oParent;
web = site.RootWeb;
}
SPList list = web.Lists["My List"];
SPField fldTitle = list.Fields.GetFieldByInternalName("Title");
fldTitle.Required = false;
fldTitle.Title = "New title";
fldTitle.Update();
}
If you have some 'strange' permissions on your web and if user have permissions to activate feature and doesn't have permissions on list you could wrap code in SPSecurity.RunWithElevatedPrivileges as @VadimLozinskiy suggested.
To summarize:
I have tested above code and I really think is valid. If you are still receiving errors on feature activation your problem is elsewhere. To troubleshoot it try to build another simple feature using above code to test if your environment is 'acting as expected'.
web.AllowUnsafeUpdates = true. Where exactly are you using this code (webpart, event receiver....)? Can you include all code you are using:SPWeb webdefinition for start. – Vedran Rasol Sep 8 '11 at 14:15SPSite curSite = (SPSite)properties.Feature.Parent; SPWeb web = curSite.RootWeb;– WCHolland Sep 8 '11 at 14:45