Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
995
How to sort nodes on a different column?
posted

I have an explorer like tree which is bound to a datasource. I want to be able to sort by something other than the text of the node. For example, I have a "NodeType" field and the value is either Folder or File. I want all Folders to be on top, and for a bonus, files sorted by FileName (which is the text of the node) ascending.

I have heard there is a SortComparer thing that I can do but do not have any examples for it. Can someone help out with this? Also, is it possible to tell the tree or the sort comparer to Sort by NodeType first and then by FileName?

 Thanks.

  • 907
    posted

    Here is an example compare function that I use

     

    public class AliTreeSortComparer : IComparer { public AliTreeSortComparer() {

    }

    #region IComparer Members

    public int Compare(object x, object y) {

    UltraTreeNodeCell cellX = x as UltraTreeNodeCell;

    UltraTreeNodeCell cellY = y as UltraTreeNodeCell;

    UltraTreeNode nodeX = x as UltraTreeNode;

    UltraTreeNode nodeY = y as UltraTreeNode;

    if (cellX != null) {

    nodeX = cellX.Node;

    }

    if (cellY != null) {

    nodeY = cellY.Node;

    }

    AliObject aliObjX = nodeX.Tag as AliObject; AliObject aliObjY = nodeY.Tag as AliObject;

    //

    // If the ALI object is null, then it is a folder.

    // We want folder to be sorted on the top and ALI objects to be sorted on the bottom.

    //

    if (aliObjX == null && aliObjY != null) {

    return -1;

    } else if (aliObjX != null && aliObjY == null) {return 1;

    }

    return string.Compare(nodeX.Key, nodeY.Key);

    }

    #endregion

    }

  • 469350
    Offline posted

    Hi,

    I don't have a sample of this, but it's really pretty easy.

    What you do is define a class that implements the IComparer interface. This interface has only one method called Compare. So you implement the Compare method, then set the SortComparer on the tree column to an instance of your IComparer class. 

    The implementation of the Compare method will pass you two objects, x and y. In the case of the tree, these objects will be TreeNodes. So you can examine the two nodes and you return a value from Compare indicating which node is greater. 

    Let me know if you get stuck and I will try to point you in the right direction.