Skip to main content

How to: Keep Links Sorted

  • 2 minutes to read

The NavLinkCollection.SortByCaption method allows you to sort a NavBar group’s links by their captions. The following code shows how to maintain sort order when new links are added to groups.

The CollectionChanged event of a group’s NavBarGroup.ItemLinks collection allows you to respond to the link collection changing.

Note: this event is not raised when a link’s caption is changed. So, the sorting routine will not be called in this case.

using DevExpress.XtraNavBar;
//...
//Subscribe to the CollectionChanged events for all the navbar's groups
private void Form1_Load(object sender, System.EventArgs e) {
    for(int i = 0; i < navBarControl1.Groups.Count; i++)
        navBarControl1.Groups[i].ItemLinks.CollectionChanged += 
          new CollectionChangeEventHandler(ItemLinks_CollectionChanged);
}

public void ItemLinks_CollectionChanged(object sender, CollectionChangeEventArgs e) {
    if(e.Action == CollectionChangeAction.Add) {
        NavLinkCollection collection = sender as NavLinkCollection;
        collection.SortByCaption();
    }
}