How to sort items in ToolStripItemCollection?

I add rows (elements) dynamically to ToolStripItemCollection:

Dim onClickHandler As System.EventHandler = New System.EventHandler(AddressOf Symbol_Click)
Dim item As New ToolStripMenuItem(newSymbol, Nothing, onClickHandler)
SomeToolStripMenuItem.DropDownItems.Add(item)

Thus, elements are not added at a time, but one after the other based on external triggers throughout the entire program session. I would like to sort the drop-down list every time I add a new item. What are my options for achieving this?

+6
source share
3 answers

Since ToolStripItemCollectionthere is no "Sort" -Function, you should listen to the changes and write your own sort method:

Private Sub ResortToolStripItemCollection(coll As ToolStripItemCollection)
    Dim oAList As New System.Collections.ArrayList(coll)
    oAList.Sort(new ToolStripItemComparer())
    coll.Clear()

    For Each oItem As ToolStripItem In oAList
        coll.Add(oItem)
    Next
End Sub

Private Class ToolStripItemComparer Implements System.Collections.IComparer
    Public Function Compare(x As Object, y As Object) As Integer Implements System.Collections.IComparer.Compare
        Dim oItem1 As ToolStripItem = DirectCast(x, ToolStripItem)
        Dim oItem2 As ToolStripItem = DirectCast(y, ToolStripItem)
        Return String.Compare(oItem1.Text,oItem2.Text,True)
    End Function
End Class

(https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.sort)

+7

#, SpeziFish. !

private void ResortToolStripItemCollection(ToolStripItemCollection coll)
    {
        System.Collections.ArrayList oAList = new System.Collections.ArrayList(coll);
        oAList.Sort(new ToolStripItemComparer());
        coll.Clear();

        foreach (ToolStripItem oItem in oAList)
        {
            coll.Add(oItem);
        }
    }

public class ToolStripItemComparer : System.Collections.IComparer
{
    public int Compare(object x, object y)
    {
        ToolStripItem oItem1 = (ToolStripItem)x;
        ToolStripItem oItem2 = (ToolStripItem)y;
        return string.Compare(oItem1.Text, oItem2.Text, true);
    }
}
+3

If we need to sort the elements in ToolStripItemCollection, we can use the following:

ItemCollection.OfType<ToolStripItem>().OrderBy(x => x.Text).ToArray(); 
0
source

All Articles