DEV Community

Cover image for In C# how do I use the FieldCollection class Add method for adding columns to shaprepoint lists?
xarzu
xarzu

Posted on

In C# how do I use the FieldCollection class Add method for adding columns to shaprepoint lists?

This is what bing ai copilot says:

using Microsoft.SharePoint.Client;

ClientContext clientContext = new ClientContext("https://yoursharepointsiteurl");
List targetList = clientContext.Web.Lists.GetByTitle("Your List Title");

// Define the new field
FieldCreationInformation newFieldInfo = new FieldCreationInformation(FieldType.Text)
{
    DisplayName = "New Column",
    InternalName = "NewColumn",
    Group = "Custom Columns",
    AddToDefaultView = true
};

// Add the new field to the list
Field newField = targetList.Fields.Add(newFieldInfo);
clientContext.ExecuteQuery();

Console.WriteLine("New column added successfully.");

Enter fullscreen mode Exit fullscreen mode

This does not help. I have some string types for columns, datetime tyhpes for columns, and some double types for columns. This bit of code does not explain how I manage to add those column types.

So I asked chatgpt.com

in C# how do I use the FieldCollection class Add method for adding columns to shaprepoint lists?

using Microsoft.SharePoint;
using System;

namespace SharePointAddColumnExample
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SPSite site = new SPSite("http://yoursitecollection"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    // Get the list where you want to add the column
                    SPList list = web.Lists["Your List Name"];

                    // Check if the field (column) already exists to avoid duplication
                    if (!list.Fields.ContainsField("New Column"))
                    {
                        // Add a new text column (single line of text)
                        list.Fields.Add("New Column", SPFieldType.Text, false);

                        // Update the list to save changes
                        list.Update();

                        Console.WriteLine("Column added successfully.");
                    }
                    else
                    {
                        Console.WriteLine("Column already exists.");
                    }
                }
            }
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

But this does nto work because this is an error:
// Add a new text column (single line of text)
list.Fields.Add("New Column", SPFieldType.Text, false);

the Add methode for Fields does not take three arguments

Top comments (0)