Create Multilevel Subtasks In A Task List Using CSOM

In this blog, we will see how to change the task list structure and make it into subtasks. Task list has a hidden field “ParentID” which is of lookup type. We need to set lookupValueCollection using the root task item’s ID value and assign its value to the ParentID field of the item that we are willing to add as a subtask.
 
Through the below code, we will create subtasks in a task list using CSOM programmatically.
  1. using System;  
  2. using System.Security;  
  3. using Microsoft.SharePoint.Client;  
  4. namespace MultiLevelTaskList {  
  5.     class Program {  
  6.         static void Main(string[] args) {  
  7.             ClientContext context = new ClientContext("https://domain /sites/demosite");  
  8.             string password = "password";  
  9.             string user = "[email protected]";  
  10.             SecureString secureString = new SecureString();  
  11.             foreach(char c in password.ToCharArray()) {  
  12.                 secureString.AppendChar(c);  
  13.             }  
  14.             SharePointOnlineCredentials cred = new SharePointOnlineCredentials(user, secureString);  
  15.             context.Credentials = cred;  
  16.             List list = context.Web.Lists.GetByTitle("TaskListWithSubtask");  
  17.             ListItem listItem = list.GetItemById(2);  
  18.             context.Load(listItem);  
  19.             context.ExecuteQuery();  
  20.             var lookupValue = new FieldLookupValue();  
  21.             lookupValue.LookupId = 1; // Get parent item ID and assign it value in lookupValue.LookupId  
  22.             var lookupValueCollection = new FieldLookupValue[1];  
  23.             lookupValueCollection.SetValue(lookupValue, 0);  
  24.             listItem["ParentID"] = lookupValueCollection; // set chidl item ParentID field  
  25.             listItem.Update();  
  26.             context.ExecuteQuery();  
  27.         }  
  28.     }  
  29. }  
Result
 
Create Multilevel Subtasks In A Task List Using CSOM
 
The above image shows the task list without having subtask.
 
After the code executes, we can see the task list having a hierarchical structure. The below Images show task list having subtasks.
 
Create Multilevel Subtasks In A Task List Using CSOM
 
Create Multilevel Subtasks In A Task List Using CSOM