如何对CheckedListBox进行排序

时间:2014-07-29 10:56:39

标签: c# .net winforms sorting checkedlistbox

我有一个 CheckedListBox ,如下所示:

  • 水果
  • ..... 香蕉
  • ..... 苹果
  • 国家
  • 汽车
  • ..... 马鲁蒂
  • ..... 丰田
  • 飞机
  • 学生
  • 动物

虽然斜体字实际上不是子节点,但被视为父节点的子节点。例如。 Banana & Apple 是Fruit的孩子,所以他们一起去等。

直接排序不起作用,因为这不会对子节点与父节点进行排序。 我必须以这样的方式对它进行排序:子节点与其各自的父节点保持一致,父节点被排序,每个父节点中的子节点也是如此。

对于Eg。 o / p应该是

  • 动物
  • 汽车
  • ..... 马鲁蒂
  • ..... 丰田
  • 国家
  • 水果
  • ..... 苹果
  • ..... 香蕉
  • 飞机
  • 学生

2 个答案:

答案 0 :(得分:1)

在评论中注意到,您可以使用树视图来更好地显示此关系。 You can put check boxes on nodes in a treeview 然后,对你正在做的事情进行排序将更加隐含,并且这种关系将更加明显。

然而。 如果你希望对CheckedListBox使用自定义排序,你可能必须创建自己的控件派生自CheckedListBox,override the "Sort" Method to provide your own sorting methodology.

// This class inherits from CheckedListBoxand implements a different  
// sorting method. 
public class SortSpecialCheckedListBox:
    CheckedListBox

{
    public SortSpecialCheckedListBox() : base()
    {        
    }

    // Overrides the parent class Sort to perform the specialised sorting
    // behaviour you are interested in
    protected override void Sort()
    {
        // Do your specialised sort here.
    }
}

答案 1 :(得分:1)

你可以制作一个List< String>其中每个父字符串都保持不变,每个子节点都有父节点作为前缀。

  • 水果
  • 水果香蕉
  • Fruits Apple
  • 国家
  • 汽车
  • Cars Maruti
  • 汽车丰田
  • 飞机

对此进行排序(按字母顺序排列)后,父排序将排在孩子面前。然后从已排序的List< String>。

重建CheckedListBox.Items

如果存在潜在的歧义,您可能想要使用不同的分隔符,否则某些字符不会被使用。