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.
- using System;
- using System.Security;
- using Microsoft.SharePoint.Client;
- namespace MultiLevelTaskList {
- class Program {
- static void Main(string[] args) {
- ClientContext context = new ClientContext("https://domain /sites/demosite");
- string password = "password";
- string user = "[email protected]";
- SecureString secureString = new SecureString();
- foreach(char c in password.ToCharArray()) {
- secureString.AppendChar(c);
- }
- SharePointOnlineCredentials cred = new SharePointOnlineCredentials(user, secureString);
- context.Credentials = cred;
- List list = context.Web.Lists.GetByTitle("TaskListWithSubtask");
- ListItem listItem = list.GetItemById(2);
- context.Load(listItem);
- context.ExecuteQuery();
- var lookupValue = new FieldLookupValue();
- lookupValue.LookupId = 1;
- var lookupValueCollection = new FieldLookupValue[1];
- lookupValueCollection.SetValue(lookupValue, 0);
- listItem["ParentID"] = lookupValueCollection;
- listItem.Update();
- context.ExecuteQuery();
- }
- }
- }
Result
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.