private async Task AddChildDetailAsync(TreeNode selectedNode) { using (var addChildDetailForm = new AddChildForm(_formsHelper)) { if (addChildDetailForm.ShowDialog() == DialogResult.OK) { List <DetailInTreeView> addedChildDetails = null; try { addedChildDetails = await _detailService.AddChildDetailAsync( SelectedNodeTag.DetailId, addChildDetailForm.EnteredName, addChildDetailForm.CountToAdd); } catch (BusinessLogicException e) { ShowMessageDialog(e.Message); return; } var addedDetailId = addedChildDetails .FirstOrDefault(x => x.Name == addChildDetailForm.EnteredName).DetailId; var detailHierarchyIds = await _detailService .GetDetailHierarchyIdsAsync(SelectedNodeTag.DetailId); // Handle case when detail is already present in the selected scope var detailNodes = new List <TreeNode>(); detailHierarchyIds.ForEach(detailHierarchyId => { var detailNode = treeView.Nodes .Find(detailHierarchyId.ToString(), true) .SingleOrDefault(); if (detailNode != null) { detailNodes.Add(detailNode); } }); detailNodes.ForEach(detailNode => { var detailNodeTag = detailNode.Tag as DetailInTreeView; var targetNodeHierarchyId = HierarchyId .Parse($"{detailNodeTag.HierarchyLevel}{addedDetailId}/"); var addedDetail = addedChildDetails .SingleOrDefault(x => x.HierarchyLevel == targetNodeHierarchyId); var targetNodeToUpdate = treeView.Nodes .Find(targetNodeHierarchyId.ToString(), true) .SingleOrDefault(); var parentNode = detailNode.Parent; DetailInTreeView parentNodeTag = parentNode == null ? null : parentNode.Tag as DetailInTreeView; // Update only if children already loaded for the detail // for which child detail is beening added if (parentNodeTag == null || parentNodeTag.IsThirdGenLoaded) { var detailNodeHierarchyId = detailNodeTag.HierarchyLevel; // Handle case when detail is already present in the selected scope if (targetNodeToUpdate != null) { targetNodeToUpdate.Text = DetailNameInTree(addedDetail.Name, addedDetail.Count); targetNodeToUpdate.Tag = addedDetail; } // Handle case when detail is NOT present in the selected scope if (targetNodeToUpdate == null) { var addedNodeIndex = detailNode.Nodes.Add(new TreeNode { Text = DetailNameInTree(addedDetail.Name, addedDetail.Count), Tag = addedDetail, Name = targetNodeHierarchyId.ToString() }); if (detailNodeTag.IsThirdGenLoaded) { var addedNode = detailNode.Nodes[addedNodeIndex]; addedChildDetails.ForEach(addedChildDetail => { if (addedDetail.HierarchyLevel == addedChildDetail.HierarchyLevel.GetAncestor(1)) { addedNode.Nodes.Add( new TreeNode { Text = DetailNameInTree(addedChildDetail.Name, addedChildDetail.Count), Tag = addedChildDetail, Name = addedChildDetail.HierarchyLevel.ToString() }); } }); } } } }); ShowMessageDialog("Success added!"); } } }