# Sorting the Properties

There are several ways to specify the sort order of the PropertyGrid. This may be necessary after using SelectedObject(s), which results in categories and Properties being ordered according to the TypeConverter or TypeDescriptor classes.

# Ordering on attributes

Applying the SortedCa*tegory attribute or the SortedProperty attribute enables you to specify the sort order.

# SortedCategory attribute

The PropertyGrid sorts parent categories by ascending order of the index placed in SortedCategory attribute (if applied instead of the usual Category attribute). Those without SortedCategory set appear below the rest, in order of discovery by reflection.

# > Example

This places the category “Appearance” in the 4th position amongst the root categories:

[SortedCategory("Appearance", 4)]
public int MyProperty1 {
    ...

[SortedCategory("Appearance", 4)]
public int MyProperty2 {
    ...

# SortedProperty attribute

The SortedProperty attribute acts like SortedCategory (above), but for child Properties inside a parent category.

# > Example

This sorts three properties at the same level in the order MyProperty3, MyProperty1 and MyProperty2:

[SortedProperty(2)]
public int MyProperty1 {
    ...

public int MyProperty2 {
    ...

[SortedProperty(1)]
public int MyProperty3 {
    ...

# Using a PropertyComparer

Sometimes a complex sorting mechanism is required. Achieve this by assigning a custom PropertyComparer, derived from the IComparer class.

PropertyComparerDefaultSort class is the default, which sorts alphabetically. Two others are provided: PropertyComparerNoSort will allow the grid to be categorized (with categories in no particular order) but non sorted (properties are displayed in the order they are published by the target instance(s)) and PropertyComparerCatSortPropNoSort will allow the grid to be categorized (categories will be sorted alphabetically) but non sorted (properties are displayed in the order they are published by the target instance(s)).

The selected PropertyComparer compares PropertyDescriptor instances, so the code of your comparer class should look like this:

public class MyPropertyComparer : IComparer
{
    public int Compare(object x, object y)
    {
        PropertyDescriptor p1 = x as PropertyDescriptor;
        PropertyDescriptor p2 = y as PropertyDescriptor;

        if (p1.Equals(p2))
            return 0;

Note that the Compare method should return 0 in only one case, when both arguments are truly equal. In all other cases, return -1 or 1 (for example, the default alphabetical sorting could be tempted to return 0 for two PropertyDescriptor whose DisplayName properties are the same. Instead, -1 will be returned).

Assign it to the grid before calling SelectedObject(s):

myGrid.PropertyComparer = new MyPropertyComparer();
myGrid.SelectedObject = myTargetInstance;
Last Updated: 5/25/2022, 1:18:09 PM