Monday, February 26, 2007

How to add a site column to a list by code

A colleague just asked me how to add a site column defined in the root web to a list somewhere in the site, so here is the small snippet:

private void AddSiteColumnToList(string sitePath, string listName, string columnName)
{
     using (SPSite site = new SPSite(sitePath))
     {
          using (SPWeb web = site.OpenWeb())
          {
                //Since the site column is on the root web,
                //we need to get the root web
                //If it was'nt on the root web, but instead on the same site as the 
                //list, we could have just used the "web" object
                using (SPWeb root = site.RootWeb)
                {
                     //get 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();
                 }
           }
      }
}

2 comments:

Ton Stegeman said...

It is even easier than that. You can use the AvailableFields property of your SPWeb object.

Ton

Edward said...

Hi,
I love your blog ! Mind to exchange links ? Email me if you are interested

Cheers,
Edward