【问题标题】:C# custom combobox sortingC# 自定义组合框排序
【发布时间】:2010-11-25 14:01:17
【问题描述】:

是否可以在组合框中自定义排序/显示顺序?假设我想要一个特殊值“MasterValue”在所有其他人之前。

【问题讨论】:

    标签: c# winforms combobox


    【解决方案1】:

    创建一个实现 IComparable 并覆盖 ToString 的类,而不是添加字符串。

    将该类的实例添加到您的 ComboBox

    【讨论】:

    • 好的,但我仍然希望“MasterValue”作为显示值,并根据所有对象的 ToString() 值进行排序,除了应该在顶部的“MasterValue”。你的回答有用吗?
    • @Duaner:想法是组合框对调用 IComparable 接口的 CompareTo 函数的元素进行排序。您需要做的是围绕 String 类创建一个包装器。 ToString 在组合框中返回您想要的字符串,而 CompareTo 确保您有想要的顺序。如果字符串是“MasterValue”,CompareTo 总是返回
    • 这在 .NET 3.5 中对我不起作用。 System.Windows.Forms.ComboBox 有它的内部 ItemComparer 类,它实际上调用 GetItemText() 属性,该属性调用 ToString() 而不是 IComparable 接口。
    • 我在 Framework 2 中也有同样的体验。尽管 ComboBox.Sorted = true,但从未调用过 IComparable.CompareTo 函数。
    • 这个答案是错误的。 IComparable 永远不会被调用! (框架4)为什么这是4票赞成的公认答案???
    【解决方案2】:

    下面的代码可以解决问题。

    1. 为要排序的项目创建一个单独的列表,然后使用 AddRange。

      comboBox1.Items.Add("Master");
      
      List<String> listToSort = new List<String>();
      
      listToSort.Add("6nd");
      listToSort.Add("3nd");
      listToSort.Add("5nd");
      listToSort.Add("4nd");
      listToSort.Add("2nd");
      
      listToSort.Sort();
      
      comboBox1.Items.AddRange(listToSort.ToArray<String>());
      

    【讨论】:

    • 第二,第三,四?
    【解决方案3】:

    创建一个数据源作为视图(即存储过程),它返回一个额外的字段值 1。

    然后获取数据源,并在数据视图中添加一个附加行,附加字段的值为 0。

    然后对视图进行排序,最初按该字段,然后按该字段的描述。

    这将始终将您的“主值”放在首位,然后按字母顺序对其他值进行排序。

    private void PopulateCombo()
    {
       // get data view that returns 3 columns, 
       //master sort column set to 1, id, and description //
      DataView view = GetSource();
    
      // add a new row to the data source that has column values
      // 0 for master sort column (all others are returned 1
      // an appropriate ID and a description
      // data view columns = master sort column, id, description    
      view.Table.Rows.Add(new object[] {0, 1, "MasterValue"});
    
      // sort first by master column then description //
      view.Sort = "MasterSortColumn ASC, Description ASC"; 
    
      combo.DataSource = view;
      combo.ValueMember = "Id";
      combo.DisplayMember = "Description";
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-13
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      相关资源
      最近更新 更多