C# custom combobox sorting

后端 未结 3 2037
醉酒成梦
醉酒成梦 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";
    }
    

提交回复
热议问题