Create Task in Task list – C#

SharePoint onPrem 2013, 2016, 2019

Create SharePoint list item has the same logic but for task list you will need assigned to.

Assigned to is site column if type people or hyperlink. So, it’s expecting to send by code a valid SharePoint user and this can be done by using EnsureUser and SPFieldUserValue .

EnsureUser –> will retrieve a valid SPUser

SPFieldUserValue –> will take the SPUser and retrieve and save the data in correct format.

using (SPSite site = new SPSite("https://serverName/sites/TEST"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists.TryGetList("Tasks");
                    if (list != null)
                    {
                        // get the SharePoint group
                        SPUser user = web.EnsureUser(@"domainName\userName");
 
                        // Create a new task item
                        SPListItem task = list.Items.Add();
                        SPFieldUserValue assignTo = new SPFieldUserValue(web, user.ID, user.Name);
                        task["AssignedTo"] = assignTo; 
                        task["Title"] = "Testing";
                        task["Description"] = "Testing";                       
                        task.Update();
                    }
                }
            }
        }