简体   繁体   中英

Turn off sorting for branch in a TreeView

I have a Winforms Treeview with nodes in several levels and branches. The position of the nodes in the tree are important. I need to have some branches unsorted, while the rest of the nodes in the treeview sorted. I also need to be able to turn the sorting on/off by code according to user input.

From what I can read and google the winform treeview component can only be sorted or unsorted as a whole. All or nothing. Is that correct, so I have to write the sorting mecanism myself, or did I miss something?

I don't know about ignoring branches when it comes to sorting, but if you just want to sort a single branch, you can try this old school method:

private void SortBranch(TreeNode parentNode) {
  TreeNode[] nodes;
  if (parentNode == null) {
    nodes = new TreeNode[treeView1.Nodes.Count];
    treeView1.Nodes.CopyTo(nodes, 0);
  } else {
    nodes = new TreeNode[parentNode.Nodes.Count];
    parentNode.Nodes.CopyTo(nodes, 0);
  }
  Array.Sort(nodes, new TreeSorter());
  treeView1.BeginUpdate();
  if (parentNode == null) {
    treeView1.Nodes.Clear();
    treeView1.Nodes.AddRange(nodes);
  } else {
    parentNode.Nodes.Clear();
    parentNode.Nodes.AddRange(nodes);
  }
  treeView1.EndUpdate();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM