SharePoint

How to add new Field in Existing SharePoint List

Here , I will show how we can add new Field in our existing SP List of Existing system .
In My case , Existing List Name is ::: MyList
Let , Our SP Site Collection has many sites and I dont know the actual number of Sites , But I need to Add Field in every Site , So we can do like below , which will add in all Sites inside of a Site Collection .
and strSiteURL is The URL of my Site Collection .

string strListName = "MyList";
SPField oSPField = null;
bool blnColumnFileTypeExist = true;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite oSPsite = new SPSite(strSiteURL))
{
foreach (SPWeb oSPWeb in oSPsite.AllWebs)
{
SPList lst = null;
oSPWeb.AllowUnsafeUpdates = true;
try
{
lst = oSPWeb.Lists[strListName];
}
catch(Exception ex)
{
continue;
}
try
{
oSPField = lst.Fields.GetField("FileType");
}
catch
{
blnColumnFileTypeExist = false;
}
if (!blnColumnFileTypeExist)
{
SPFieldText fldFileType = (SPFieldText)lst.Fields.CreateNewField(SPFieldType.Text.ToString(), "FileType");
fldFileType.ReadOnlyField = false;
lst.Fields.Add(fldFileType);
lst.Update();
}
}
}
});

Standard

Leave a Reply

Your email address will not be published. Required fields are marked *