How to sort items in ToolStripItemCollection?

核能气质少年 提交于 2019-12-05 06:21:48
SpeziFish

Since ToolStripItemCollection has no "Sort"-Function, you have to listen on 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

You have to use your own comparer (https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.sort)

This post was tagged as c# so I converted it based on SpeziFish's answer. Thanks!

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);
    }
}
Sandy

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

ItemCollection.OfType<ToolStripItem>().OrderBy(x => x.Text).ToArray(); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!