I am trying to fill the TreeView, but the program steadily drops out with a stack overflow

standard Id, ParentID, Name structure

private void UpdateTreeView() { trvMain.Nodes.Clear(); var list = _datamanager.Department.GetList(); var root = trvMain.Nodes.Add("Root"); root.Tag = 0; BindTree(list, root); trvMain.ExpandAll(); } public void BindTree(IEnumerable<Department> list, TreeNode parentNode) { var nodes = list.Where(x => parentNode == null ? x.ParentId == 0 : x.ParentId == parentNode.Tag.ToInt()); foreach (var node in nodes) { var _node = new TreeNode() { Name = "id" + node.Id.ToString(), Text = node.Name, Tag = node.ParentId }; if (parentNode == null) { trvMain.Nodes.Add(_node); } else { parentNode.Nodes.Add(_node); } BindTree(list, _node); } } 
  • one
    So what is this language? Java? - Riĥard Brugekĥaim
  • one
    Well, the exit condition from recursion obviously does not work ( nodes are not always empty). Need to look at examples of the structure list - tutankhamun
  • " parentNode == null ? x.ParentId == 0 : x.ParentId == parentNode.Tag.ToInt() " - what does this string do? first == it is clear for what, and for what the others == ? - Stack
  • @RihardBrugekhaim well, obviously not java. Where in var var? Definitely with # - dirkgntly

1 answer 1

Overflow of the stack is due to the fact that there is no condition for stopping recursion.
In the next method

 void BindTree(IEnumerable<Department> list, TreeNode parentNode) { var nodes = list.Where(...); foreach (var node in nodes) { ... BindTree(list, _node); } } 

one must determine the correct condition in list.Where. As a result, the nodes will be empty under certain conditions, the BindTree will not be called, and the recursion will stop.