/// <summary> /// Determines the correct position in the control tree of <paramref name="targetList"/> /// where <paramref name="control"/> should be inserted. /// </summary> /// <param name="sourceList">The source list.</param> /// <param name="targetList">The target list.</param> /// <param name="control">The control.</param> /// <param name="addedControls">The control ids that have been added to the target.</param> /// <returns>The correct position in the control tree of <paramref name="targetList"/> /// where <paramref name="control"/> should be inserted.</returns> private int DetermineTargetIndex(ControlList sourceList, ControlList targetList, Control control, List<int> addedControls) { int sourceIndex = sourceList.IndexOf(control.Id); int returnValue = sourceIndex; if (sourceIndex >= targetList.Count) { return sourceIndex; } for (int i = sourceIndex; i >= 0; i--) { if (addedControls.Contains(targetList[i].Id)) { returnValue++; } } return returnValue >= 0 ? returnValue : 0; }