在c#winforms中填充树视图后,对树视图的子节点进行排序 [英] Sorting child nodes of a treeview after populating the treeview in c# winforms
问题描述
在我的winforms程序中,无法对Treeview的子节点进行排序.我的树视图由一些XML文件填充,并且它使用xml文件中的内部文本作为节点的Text属性(因此,我认为在将它们添加到树视图之前,如果可能的话,我无法对其进行排序,因为xml文件是尺寸很大,我不想浪费这个过程).我的程序中填充的树视图如下所示:
I am having trouble sorting child nodes of a treeview in my winforms program. My treeview is populated by some XML files and it uses an internal text inside the xml files as Text property of nodes (So I think I cant sort them before adding them to the tree view, or if it is possible, since the xml files are big in size I dont want to waste the process). A populated treeview in my program looks like this:
您可以猜到我希望子节点排序(我不希望HBM \ D10出现在HBM \ D1之后),而是我想要:
As you can guess I want child nodes to sort like (I dont want HBM\D10 to come after HBM\D1) rather I want:
HBM\D1
HBM\D2
HBM\D3
etc...
我已经尝试过treeView1.Sort(),并且还添加了beginUpdate和endUpdate,但是我没有成功:(
I have already tried treeView1.Sort() and also adding beginUpdate and endUpdate but I had no suceess :(
我正在使用.NET 4,任何技巧都会得到应用
I am using .NET 4, any tips would be appriciated
好吧,我根据托马斯的建议进行了整理:
class NodeSorter : IComparer
{
public int Compare(object x, object y)
{
TreeNode tx = (TreeNode)x;
TreeNode ty = (TreeNode)y;
if (tx.Text.Length < ty.Text.Length)
{
return -1;
}
if (tx.Text.Length > ty.Text.Length)
{
return 1;
}
return 0;
}
}
推荐答案
您需要创建一个自定义比较器并将其分配给TreeViewNodeSorter
属性:
You need to create a custom comparer and assign it to the TreeViewNodeSorter
property:
public class NodeSorter : System.Collections.IComparer
{
public int Compare(object x, object y)
{
TreeNode tx = (TreeNode)x;
TreeNode ty = (TreeNode)y;
// Your sorting logic here... return -1 if tx < ty, 1 if tx > ty, 0 otherwise
...
}
}
...
treeView.TreeViewNodeSorter = new NodeSorter();
treeView.Sort();
这篇关于在c#winforms中填充树视图后,对树视图的子节点进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!