[c#] SharePoint : How can I programmatically add items to a custom list instance

I am really looking for either a small code snippet, or a good tutorial on the subject.

I have a C# console app that I will use to somehow add list items to my custom list. I have created a custom content type too. So not sure if I need to create an C# class from this content type too. Perhaps not.

Thanks in advance

This question is related to c# sharepoint content-type

The answer is


To put it simple you will need to follow the step.

  1. You need to reference the Microsoft.SharePoint.dll to the application.
  2. Assuming the List Name is Test and it has only one Field "Title" here is the code.

            using (SPSite oSite=new SPSite("http://mysharepoint"))
        {
            using (SPWeb oWeb=oSite.RootWeb)
            {
                SPList oList = oWeb.Lists["Test"];
                SPListItem oSPListItem = oList.Items.Add();
                oSPListItem["Title"] = "Hello SharePoint";
                oSPListItem.Update();
            }
    
        }
    
  3. Note that you need to run this application in the Same server where the SharePoint is installed.

  4. You dont need to create a Custom Class for Custom Content Type


This is how it was on the Microsoft site, with me just tweaking the SPSite and SPWeb since these might vary from environment to environment and it helps not to have to hard-code these:

using (SPSite oSiteCollection = new SPSite(SPContext.Current.Site.Url))
{
    using (SPWeb oWeb = oSiteCollection.OpenWeb(SPContext.Current.Web))
    {
        SPList oList = oWeb.Lists["Announcements"];
        // You may also use 
        // SPList oList = oWeb.GetList("/Lists/Announcements");
        // to avoid querying all of the sites' lists
        SPListItem oListItem = oList.Items.Add();
        oListItem["Title"] = "My Item";
        oListItem["Created"] = new DateTime(2004, 1, 23);
        oListItem["Modified"] = new DateTime(2005, 10, 1);
        oListItem["Author"] = 3;
        oListItem["Editor"] = 3;
        oListItem.Update();
    }
}

Source: SPListItemClass (Microsoft.SharePoint). (2012). Retrieved February 22, 2012, from http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem.aspx.


You can create an item in your custom SharePoint list doing something like this:

using (SPSite site = new SPSite("http://sharepoint"))
{
    using (SPWeb web = site.RootWeb)
    {
        SPList list = web.Lists["My List"];
        SPListItem listItem = list.AddItem();
        listItem["Title"] = "The Title";
        listItem["CustomColumn"] = "I am custom";
        listItem.Update();
     }
}

Using list.AddItem() should save the lists items being enumerated.


I had a similar problem and was able to solve it by following the below approach (similar to other answers but needed credentials too),

1- add Microsoft.SharePointOnline.CSOM by tools->NuGet Package Manager->Manage NuGet Packages for solution->Browse-> select and install

2- Add "using Microsoft.SharePoint.Client; "

then the below code

        string siteUrl = "https://yourcompany.sharepoint.com/sites/Yoursite";
        SecureString passWord = new SecureString();

        var password = "Your password here";
        var securePassword = new SecureString();
        foreach (char c in password)
        {
            securePassword.AppendChar(c);
        }
        ClientContext clientContext = new ClientContext(siteUrl);
        clientContext.Credentials = new SharePointOnlineCredentials("[email protected]", securePassword);/*passWord*/
        List oList = clientContext.Web.Lists.GetByTitle("The name of your list here");
        ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
        ListItem oListItem = oList.AddItem(itemCreateInfo);
        oListItem["PK"] = "1";
        oListItem["Precinct"] = "Mangere";
        oListItem["Title"] = "Innovation";
        oListItem["Project_x005F_x0020_Name"] = "test from C#";
        oListItem["Project_x005F_x0020_ID"] = "ID_123_from C#";
        oListItem["Project_x005F_x0020_start_x005F_x0020_date"] = "2020-05-01 01:01:01";
        oListItem.Update();

        clientContext.ExecuteQuery();

Remember that your fields may be different with what you see, for example in my list I see "Project Name", while the actual value is "Project_x005F_x0020_ID". How to get these values (i.e. internal filed values)?

A few approaches:

1- Use MS flow and see them

2- https://mstechtalk.com/check-column-internal-name-sharepoint-list/ or https://sharepoint.stackexchange.com/questions/787/finding-the-internal-name-and-display-name-for-a-list-column

3- Use a C# reader and read your sharepoint list

The rest of operations (update/delete): https://docs.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ee539976(v%3Doffice.14)


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to sharepoint

SharePoint 2013 get current user using JavaScript "Object doesn't support this property or method" error in IE11 How to open SharePoint files in Chrome/Firefox Powershell Error "The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function..." Error :The remote server returned an error: (401) Unauthorized Best way to resolve file path too long exception Could not load file or assembly '' or one of its dependencies Reasons for a 409/Conflict HTTP error when uploading a file to sharepoint using a .NET WebRequest? CAML query with nested ANDs and ORs for multiple fields How to pass credentials to httpwebrequest for accessing SharePoint Library

Examples related to content-type

Passing headers with axios POST request Spring MVC 4: "application/json" Content Type is not being set correctly What are all the possible values for HTTP "Content-Type" header? New lines (\r\n) are not working in email body HTML Input="file" Accept Attribute File Type (CSV) How do you set the Content-Type header for an HttpClient request? Utility of HTTP header "Content-Type: application/force-download" for mobile? Set Content-Type to application/json in jsp file Cannot set content-type to 'application/json' in jQuery.ajax Difference between application/x-javascript and text/javascript content types