4

Is it possible to display PropertyGrid items in the UI in the way they are declared? I found that they are sorted first by CategoryAttribute and then by DisplayName attribute in ascending order.

I'm using .NET version 3.5 using Visual Studio 2010 Ultimate.

EDIT

The application is a WPF application.

Donotalo
  • 12,748
  • 25
  • 83
  • 121
  • 1
    possible duplicate of [How can I customize category sorting on a PropertyGrid?](http://stackoverflow.com/questions/823327/how-can-i-customize-category-sorting-on-a-propertygrid) – Oliver Aug 07 '12 at 08:10
  • 1
    Note that *strictly speaking* there is no mechanism of guaranteeing declaration order; see [MSDN](http://msdn.microsoft.com/en-us/library/aky14axb.aspx) "The GetProperties method does not return properties in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which properties are returned, because that order varies." - and note that `TypeDescriptor` (which is used by `PropertyGrid`) can only provide what is available to it. If order isn't guaranteed, then *order isn't guaranteed*. – Marc Gravell Aug 07 '12 at 08:19

3 Answers3

8

From this doc: https://learn.microsoft.com/en-US/dotnet/api/system.windows.forms.propertysort

if you set the property PropertySort to PropertySort.NoSort the sorting order of properties should follow this criterium: Properties are displayed in the order in which they are retrieved from the TypeDescriptor.

antiduh
  • 11,853
  • 4
  • 43
  • 66
Max Lambertini
  • 3,583
  • 1
  • 19
  • 24
  • sorry, i should've mentioned that i'm working on a WPF application. i can't access System.Windows.Forms.PropertySort! – Donotalo Aug 07 '12 at 08:29
  • Then I guess you'd have to roll your own, as per this link: http://www.mindscapehq.com/blog/index.php/2008/01/27/sorting-and-grouping-in-the-wpf-property-grid/ – Max Lambertini Aug 07 '12 at 09:06
  • 2
    I found that this also works rather than NoSort. propGrid.PropertySort = PropertySort.Categorized; – thewikus May 11 '17 at 08:39
  • User .NoSort result in losing category, use categorized instead. – Ray Jul 06 '21 at 02:59
4

You can set quite a few properties using annotations, one of them is the "order of display" using the System.ComponentModel.DataAnnotations.Display Attribute would look like this:

[DisplayName("Error"),Display(Order = 5)]
public string Error { get; internal set; }
Walter Verhoeven
  • 3,867
  • 27
  • 36
1

You can try this code.

private void propertyGrid1_PropertySortChanged(object sender, EventArgs e)
{
    if (propertyGrid1.PropertySort == PropertySort.CategorizedAlphabetical)
    {
        propertyGrid1.PropertySort = PropertySort.Categorized;
    }
}