SharePoint : How can I programmatically add items to a custom list instance

后端 未结 5 1338
独厮守ぢ
独厮守ぢ 2021-02-01 17:22

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 l

5条回答
  •  别那么骄傲
    2021-02-01 18:20

    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("Username@domain.nz", 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_x0020_Name"] = "test from C#";
            oListItem["Project_x0020_ID"] = "ID_123_from C#";
            oListItem["Project_x0020_start_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_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)

提交回复
热议问题