2009-09-04 72 views
4

是否有可能在combox中有自定義排序/顯示順序?假設我在所有其他人之前想要一個特殊值「MasterValue」。C#自定義組合框排序

回答

4

而是添加字符串,創建一個實現了IComparable接口和覆蓋的ToString類。

添加該類的實例,以您的組合框

+0

好了,但我仍然想要「MasterValue」作爲顯示值,並根據除了應位於頂部的「MasterValue」之外的所有對象的ToString()值進行排序。你的答案是否有訣竅? – Toto 2009-09-04 11:00:28

+0

@Duaner:這個想法是,comboBox對調用IComparable接口的CompareTo函數的元素進行排序。你必須做的是圍繞String類創建一個包裝器。 ToString返回你想要在組合框中的字符串,並且CompareTo確保你有想要的訂單。如果字符串是「MasterValue」,那麼CompareTo總是返回一個<0,所以「MasterValue」總是第一個。 – 2009-09-04 11:09:35

+4

這在.NET 3.5中對我無效。 System.Windows.Forms.ComboBox有其內部的ItemComparer類,它實際上調用GetItemText()屬性,它調用ToString()而不是IComparable接口。 – 2010-08-27 02:07:02

4

下面的代碼將做的伎倆。

  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>()); 
    
+0

second,thirdon,fourton? – Lars 2013-11-21 13:24:17

1

創建數據源作爲一個視圖(如存儲過程),返回值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"; 
}