How to: Sort properties using the CustomPropertyDescriptors event

  • 3 minutes to read

This example shows how to display an object's properties in a PropertyGridControl in a custom order. Properties are sorted via the CustomPropertyDescriptors event.By default, properties are sorted according to their display names. To display properties in a custom order, the properties are sorted, and then the sorted collection is assigned to the event's Properties parameter.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraVerticalGrid.Events;
using System.Collections;
using System.Globalization;

namespace PropertySorting {
    public partial class Form1 : Form {
        bool allowCustomSorting = false;

        public Form1() {
            InitializeComponent();
            this.propertyGridControl1.SelectedObject = new CustomClass() { Property1 = "one", Property2 = "two", Property3 = "three", Property4 = "four", Property5 = "five" };
        }

        void propertyGridControl1_CustomPropertyDescriptors(object sender, CustomPropertyDescriptorsEventArgs e) {
            if(allowCustomSorting && e.Context.PropertyDescriptor == null) {
                e.Properties = e.Properties.Sort(new string[] { "Property5", "Property4", "Property3", "Property2", "Property1" });
            }
        }
        void button1_Click(object sender, EventArgs e) {
            allowCustomSorting = !allowCustomSorting;
            propertyGridControl1.OptionsBehavior.PropertySort = allowCustomSorting ? DevExpress.XtraVerticalGrid.PropertySort.NoSort : DevExpress.XtraVerticalGrid.PropertySort.Alphabetical;
            propertyGridControl1.Refresh();
        }
    }
    class CustomClass {
        [DisplayName("C")]
        public string Property1 { get; set; }
        [DisplayName("B")]
        public string Property2 { get; set; }
        [DisplayName("A")]
        public string Property3 { get; set; }
        [DisplayName("D")]
        public string Property4 { get; set; }
        [DisplayName("E")]
        public string Property5 { get; set; }
    }
}