C# custom combobox sorting

后端 未结 3 2001
醉酒成梦
醉酒成梦 2021-01-13 16:55

Is it possible to have a custom sort/display order in a combox ? Say I want a special value \"MasterValue\" before all the others.

相关标签:
3条回答
  • 2021-01-13 17:19

    Create a data source as a view (i.e. stored procedure) that returns an additional field valued 1.

    Then get the data source, and add an additional row to the data view, with the additional field valued at 0.

    Then sort the view, by that field initially, and then by the description of the field.

    This will always then put your 'Master Value' first, then sort the others alphabetically.

    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";
    }
    
    0 讨论(0)
  • 2021-01-13 17:25

    Instead of adding strings, create a class that implements IComparable and overrides ToString.

    Add instances of that class to your ComboBox

    0 讨论(0)
  • 2021-01-13 17:31

    The following code will do the trick.

    1. Create a separate list of the items you want to sort and then use 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 讨论(0)
提交回复
热议问题