SharePoint 2016 Logo

This post is about how to crate a list item in SharePoint list in backend process. It can be API, background service, azure function, mobile or desktop app. So, it can be anything you want, but in .Net. And we will use SharePoint Rest API, that is wrapped by CSOM (Microsoft.SharePointOnline.CSOM).

To create a new list item in SharePoint list you need to process the next 6 steps

  1. Get sharepoint context - usually with app registration
  2. Get the list from Web and load it.
  3. Initialize new item with ListItemCreationInformation
  4. Fill the fields of the new item
  5. Initialize savin the item with Update()
  6. Execute query to save the new item.

The example of the method is below:

public async Task<bool> SaveProcessingHistory(string text)
	{
		using var clientContext = await _sharePointContext.CreateContextAsync(_sharepointHRUrl);
		var list = clientContext.Web.Lists.GetByTitle("ReminderHistory");
		clientContext.Load(list);
		clientContext.ExecuteQuery();
		
		ListItemCreationInformation itemInfo = new ListItemCreationInformation();
		ListItem newItem = list.AddItem(itemInfo);
		newItem["Title"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
		newItem["ReminderHistory"] = text;
		newItem.Update();

		try
		{
			await clientContext.ExecuteQueryAsync();
			return true;
		} catch (Exception ex)
		{
			_logger.LogError($"Error on saving ReminderHistory {ex.Message}");
			return false;
		}
	}