Search code examples
c#winformsdata-annotationspropertygrid

Using display data annotations in property grid c#


I am creating a Windows Form Application in C# and using property grid in it. I am displaying properties of a Person class object in it and wanted to use Display data annotation to set property's description, display order of properties and other things. To implement the same I have added reference to System.ComponentModel.DataAnnotations in my code and code for my Person class is like this:

class Person
    {
        [Display(Name = "First Name", Order = 1,
        Prompt = "Enter First Name", Description = "Person First Name")]
        public string firstname { get; set; }
        [Display(Name = "Last Name", Order = 2,
        Prompt = "Enter Last Name", Description = "Person Last Name")]
        public string lastname { get; set; }
        [Display(Name = "Age", Order = 3,
        Prompt = "Enter Age", Description = "Person Age")]
        public int age { get; set; }
    }

But data annotations not working. Here is screenshot of property grid in my app.. screenshot of property grid

I am not able to understand why data annotation are not working in my code. Can anyone help out? Is there anything I am missing out? Do I need to implement any code segment to make them work?


Solution

  • Set the property PropertySort of your propertyGrid to PropertySort.NoSort and properties will be displayed in the order they are declared

    propertyGrid1.PropertySort = PropertySort.NoSort;