Small Town Coder

sharing code samples for desktop, web, and mobile

Visual Studio PropertyGrid Category Order

Looking for a way to control the order in which your component property categories are displayed in the PropertyGrid control? Borrowing from some other examples I found online, the following solution falls well within the definition of a hack. The PropertyGrid uses a string sorter in order to sort the category value applied to a property using the Category attribute (System.ComponentModel.CategoryAttribute) class. Unfortunately, this is the only attribute used to display categories in the PropertyGrid and does not support any ordering features. You can prefix each category name with a character (A, B, C...) or number (1,2,3...) to achieve the desired order but that doesn't look good in my opinion. The hack I was referring to earlier suggests prefixing the category name value with non-visible characters (string literals) inline with the CategoryAttribute value that would still be evaluated by the string sorter. The PropertyGrid won't display the characters when painting the category. The article I'm referring was found on the Windows Dev Center, Sorting CategoryAttributes for PropertyGrids. To me, the solution isn't all that intuitive or manageable which is why I opted to create my own class that simply inherited from CategoryAttribute with an additional variable on the constructor to indicate the priority. The PriorityCategoryAttribute Class As the name of this class suggests, it provides priority for the category. The constructor applies the hack to the category value using the supplied priority value. The greater the priority, the higher up in the PropertyGrid the category will be displayed. Visual Basic Imports System Imports System.ComponentModel Public Class PriorityCategoryAttribute Inherits System.ComponentModel.CategoryAttribute Public Sub New(category As String, priority As Integer) MyBase.New(New String(ControlChars.Tab, priority) & category) End Sub End Class C# using System; using System.ComponentModel; public class PriorityCategoryAttribute: CategoryAttribute { public PriorityCategoryAttribute(string category, int priority) : base(new string('\t', priority) + category) { } } That's all there is to it. Use the PriorityCategory attribute instead of the existing Category attribute on your properties to achieve the desired order in the PropertyGrid.