Thursday, May 29, 2008

Adding site column to the list at any site level

Hi All,

May times we require to add columns defined at root web level to any site at child level.

Here is a simple way to accomplish this :

Make one function like this :

private void AddSiteColumnToList(string sitePath, string listName, string columnName)
{
using (SPSite site = new SPSite(sitePath))
{
using (SPWeb web = site.OpenWeb())
{
using (SPWeb root = site.RootWeb)
{
//Take the site column from the root web
SPField fld = root.Fields[columnName];

//get the list from the site
SPList list = web.Lists[listName];

//add the column
list.Fields.Add(fld);

//update the list
list.Update();
}
}
}



That's it. Your job is done.

Thank you

No comments:




Share your SharePoint Experiences with us...
As good as the SharePointKings is, we want to make it even better. One of our most valuable sources of input for our Blog Posts comes from ever enthusiastic Visitors/Readers. We welcome every Visitor/Reader to contribute their experiences with SharePoint. It may be in the form of a code stub, snippet, any tips and trick or any crazy thing you have tried with SharePoint.
Send your Articles to sharepointkings@gmail.com with your Profile Summary. We will Post them. The idea is to act as a bridge between you Readers!!!

If anyone would like to have their advertisement posted on this blog, please send us the requirement details to sharepointkings@gmail.com