Question Details

No question body available.

Tags

c# winforms sorting treeview .net-10.0

Answers (2)

Accepted Answer Available
Accepted Answer
May 9, 2026 Score: 3 Rep: 438 Quality: High Completeness: 60%

Step 1 — Create the custom sorter class

Add a new file NumericNodeSorter.cs to your project (or paste the class directly into your Form file if you prefer):

using System.Collections;
using System.Globalization;

/// /// Sorts TreeView nodes using .NET 10 numeric ordering (natural sort). /// "Document2" comes before "Document10". /// public class NumericNodeSorter : IComparer { private static readonly CompareInfo compareInfo = CultureInfo.CurrentCulture.CompareInfo;

public int Compare(object? x, object? y) { string? textX = (x as TreeNode)?.Text; string? textY = (y as TreeNode)?.Text; return compareInfo.Compare(textX, textY, CompareOptions.NumericOrdering); } }

CompareOptions.NumericOrdering is new in .NET 10 — the project must target net10.0 (check in your .csproj).

Step 2 — Assign the sorter to the TreeView

Do this once, in the form constructor or FormLoad event, before any sorting happens:

private void Form1Load(object sender, EventArgs e)
{
    treeView1.TreeViewNodeSorter = new NumericNodeSorter();
}

Step 3 — Call Sort from your context menu handler

No change needed here — your existing call works as-is:

private void sortToolStripMenuItem_Click(object sender, EventArgs e)
{
    treeView1.Sort();
}

Sort() now uses NumericNodeSorter automatically. It recurses through all levels of the tree, so child nodes are sorted too.

May 9, 2026 Score: 5 Rep: 2,251 Quality: Medium Completeness: 60%

You will need a sorter class that implements IComparer interface:

public class TreeViewNodeSorter : System.Collections.IComparer
{
    public int Compare(object? x, object? y) =>
        string.Compare(((TreeNode)x!).Text, ((TreeNode)y!).Text,
            CultureInfo.CurrentCulture, CompareOptions.NumericOrdering);
}

Create the sorter in the form constructor and assign it to the TreeViewNodeSorter property:

public Form1()
{
    InitializeComponent();
    treeView1.TreeViewNodeSorter = new TreeViewNodeSorter();
    // ...
}

Before .NET10, such sorting could be implemented like this:

public class TreeViewNodeSorter : System.Collections.IComparer
{
    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
    private static extern int StrCmpLogicalW(string psz1, string psz2);

public int Compare(object? x, object? y) => StrCmpLogicalW(((TreeNode)x!).Text, ((TreeNode)y!).Text); }


From Googling I know this can get quite complicated to program...

The algorithm can be implemented in different ways, because there are characters '!'.. '/' before '0' .. '9'. But the simplest and most obvious implementation is described in words quite simply: the compared text is split into domains: numbers and the rest of the text, then these domains are compared in pairs: text as text, numbers as numbers, and the numeric domain is smaller than the text domain.