How to add site column to SharePoint list programmatically using csom

SharePoint Site columns are reusable columns that we can create once but we can use in multiple times in various lists or libraries. There are various ways we can create a site column in SharePoint. Here we will discuss how to Add site column to list programmatically using csom in SharePoint Online.

Here we will check how we can add site columns to existing SharePoint online lists or document libraries using csom (.Net managed object model code). Recently I got one requirement to add one site column to a few lists and document libraries using C#.Net (Microsoft.SharePoint.Client.dll) code.

Add site column to SharePoint list programmatically using csom

Here I have written the below method which will take a single parameter as URL (need to provide the site URL).

You can run the code from a console application using visual studio 2015.

In the below example I will add one site column name as “MySiteColumnName” to different 3 SharePoint online list.

private static IList<string> listNames = new List<string>();
public static void AddSiteColumnToExistingList(string URL)
{
listNames.Add("List1");
listNames.Add("List2");
listNames.Add("List3");
using (ClientContext ctx = new ClientContext(URL))
{
ctx.AuthenticationMode = ClientAuthenticationMode.Default;
ctx.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
foreach (string targetListName in listNames)
{
List targetList = ctx.Web.Lists.GetByTitle(targetListName);
ctx.Load(targetList);
ctx.ExecuteQuery();
string siteCols = "MySiteColumnName";
FieldCollection fieldCollection = ctx.Web.AvailableFields;
ctx.Load(fieldCollection);
ctx.ExecuteQuery();
Field myField = Enumerable.FirstOrDefault(fieldCollection, ft => ft.InternalName == siteCols);
targetList.Fields.Add(myField);
targetList.Update();
ctx.ExecuteQuery();
}
}
}
private static string GetSPOAccountName()
{
try
{
return ConfigurationManager.AppSettings["SPOAccount"];
}
catch
{
throw;
}
}
private static SecureString GetSPOSecureStringPassword()
{
try
{
var secureString = new SecureString();
foreach (char c in ConfigurationManager.AppSettings["SPOPassword"])
{
secureString.AppendChar(c);
}
return secureString;
}
catch
{
throw;
}
}

You can check out some SharePoint site column tutorials:

Once you will run the code, it will add the “MySiteColumnName” site column to all the 3 lists. I hope this will be helpful to add site column to list programmatically in SharePoint Online.

>