Click here to Skip to main content
15,920,636 members
Articles / Programming Languages / C#
Tip/Trick

Exploring the Behaviour of Property Grid

Rate me:
Please Sign up or sign in to vote.
4.18/5 (7 votes)
7 Nov 2012CPOL2 min read 50K   24   13
Exploring the behaviour and capabilities of a property grid control.

Abstract

Property grid is a control which has strong capabilities.

Property grid extracts the properties of the class and displays corresponding values. A user can display a user friendly name that can differ from the property used for the class. Property name can be displayed in a different language as well. If multi language software is needed, the user may need to display property names in more than one language, maybe with switching between the languages at runtime.

Architecture

Designing Class

The class can be designed with different attributes, to be used in property grid. These attributes belong to System.ComponentModel namespace.

Assignment of Default Property for the Class

DefaultPropertyAttribute("<PropertyName>") is the attribute which is used to create the property default to the class.

C#
[DefaultPropertyAttribute("Name")]
public class ExploringPropertyGrid
{
    public property Name
    {
        get{}
        set{}
    }
} 

The above block of code will make the property Name default while browsing the object of the class in property grid.

Other Attributes

C#
[Browsable(true)]
//Browsable attributes makes a property visible or non-visible in the property grid.

[CategoryAttribute("Settings")]
//It defines the collection group in the property grid.

[DescriptionAttribute("Name of the object")]
//It shows the text as help in the help bar.

[ReadOnlyAttribute(false)] 
//It makes the property READ ONLY in property grid. 

Editing Property the Grid

Property grid allows the user to edit the property in the grid according to the type. A boolean and an enum value shall be allowed to select from combo, while an integer type property shall be allowed to user to enter a value.

Using a Non boolean, Non enum Data Type as a Combo Editing

Here a type converter is useful to make a property editable as combo values in grid. Here is the code for sample converter. The code converts a string to combo type.

C#
public class BTypeConVerter : StringConverter 
{
    public string[] tempStr; 
    public override bool GetStandardValuesSupported
                (ITypeDescriptorContext context)
    {
        return true;
    } 
    public override bool GetStandardValuesExclusive
                (ITypeDescriptorContext context)
    { 
    return true;
    }
    public override object ConvertFrom(ITypeDescriptorContext context, 
        System.Globalization.CultureInfo culture, object value)
    { 
        return base.ConvertFrom(context, culture, value);
    }
    public override System.ComponentModel.TypeConverter.StandardValuesCollection 
        GetStandardValues(ITypeDescriptorContext context)
    {
    return new StandardValuesCollection(new string[]{ "Val1", "Val2", "Val3" }); 
    }
} 

Accessing the Class's Members in Converter Class

The other members of the converting member's class, can be accessed under the converter class, context is the access door to the class instance. In the context.Instance you can find the instance of the current context. User can cast it to the class type and can access the member in the current context. The code example shows the same method.

C#
public override System.ComponentModel.TypeConverter.StandardValuesCollection 
    GetStandardValues(ITypeDescriptorContext context)
{
    (context.Instance as ExploringPropertyGrid).Name = -----------
    //Other code here
}

Using Converter in the Property

C#
[TypeConverter(typeof(BTypeConVerter))
public string Title
{
    get{}
    set
    {
        //Set the another property values Here
    }
}  

Hiding a Property from Property Grid at Runtime

The attributes of a property can be set as read-only in runtime for property grid using a PropertyDescriptor. User can set it either in a member function of a class or in a get{} set{} section of property. The following code sets the readonly attribute of a property “DataType” to true. In the same way, the user can set it as false.

C#
PropertyDescriptor descriptor = 
    TypeDescriptor.GetProperties(this.GetType())["DataType"];
ReadOnlyAttribute attrib = 
    (ReadOnlyAttribute)descriptor.Attributes[typeof(ReadOnlyAttribute)];
FieldInfo isReadOnly = 
 attrib.GetType().GetField("isReadOnly", BindingFlags.NonPublic| BindingFlags.Instance); 
isReadOnly.SetValue(attrib, true);

Note: ReadOnlyAttribute of all the properties must be set before, like [ReadOnlyAttribute(true)], while writing the class. Otherwise, the above code will set all the property’s attributes to true.

In the same way, the Browsable attribute of any property can be set at runtime using PropertyDescriptor. Here is the code:

C#
PropertyDescriptor descriptor= 
    TypeDescriptor.GetProperties(this.GetType())["DataType"];
BrowsableAttribute attrib= 
    (BrowsableAttribute)descriptor.Attributes[typeof(BrowsableAttribute)]; 
FieldInfo isBrow = 
 attrib.GetType().GetField("browsable",BindingFlags.NonPublic | BindingFlags.Instance);
isBrow.SetValue(attrib,false);

The point to remember in both the cases is that all the attributes must be set for all properties, otherwise it will refresh all the properties of the class.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect IDS, Roma Italy
India India
Author has been working in software engineering and research since few years. The author worked and published a markable work in instrument interfacing techniques for 1m class telescopes. He is currently working in aero-navigation software research with a leading company at Europe.

Comments and Discussions

 
QuestionWhat if field is part of a collection? Pin
breitbach10-Apr-14 13:10
breitbach10-Apr-14 13:10 
First off, thank you for the VERY useful bit of code, it worked great for me.
What is still perplexing me is one of the fields in the data displayed in the property grid is a Collection that expands. So there are a dozen or so fields in an object and the object repeats, each with unique data. I need to hide different fields in each of the repeated objects.
For example, one field in the object looks like:
[ReadOnly(false), Browsable(true)]
public float Force
{
get
{
// if the property grid is displayed
PropertyDescriptor descriptor = TypeDescriptor.GetProperties(this.GetType())["Force"];
BrowsableAttribute attribute = (BrowsableAttribute) descriptor.Attributes[typeof(BrowsableAttribute)];
System.Reflection.FieldInfo fieldToChange = attribute.GetType().GetField("browsable",
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance);
fieldToChange.SetValue(attribute, this.GetsTack);
// end of if the property grid is displayed
return force;
}
}

Force and GetsTack are two Properties in the object that is in the List of this object.
In the property grid display, the Force property is sometimes visible and sometimes not visible, but not relevant to the value in the GetsTack field.
I have this issue with all the fields in the List and only those fields in the List.
The object in the List includes a class with Properties that I am conditionally hiding fields in, and these fields all work correctly, even though they are in the List, this class is not a list. While tracing I did see that this.GetType() and this.GetsTack in each iteration are refering to the same object, I can tell from an ID field in the object. It seems that the browsable attribute affected either may not pertain to the display of this object, or it gets stomped on later in the iteration through the list. I will try to put this in a stand alone program to reproduce more simply. I hope this made sense.

Thank you for your time,
gary
QuestionRe: What if field is part of a collection? Pin
breitbach28-Apr-14 10:18
breitbach28-Apr-14 10:18 
Questiongive a sample Pin
wuzhenda21-Nov-13 13:59
wuzhenda21-Nov-13 13:59 
QuestionWhat is ["DataType"] mean here ?? Pin
Prashant Raiyani13-Nov-13 23:02
Prashant Raiyani13-Nov-13 23:02 
QuestionCode not working Pin
omzz12-Jul-13 0:03
omzz12-Jul-13 0:03 
QuestionChange Browsable attribute for enum member Pin
Valery Koval27-Dec-12 5:11
Valery Koval27-Dec-12 5:11 
BugHiding the Property Bug & its Solution Pin
sanjay_mcpd17-Oct-12 21:32
sanjay_mcpd17-Oct-12 21:32 
GeneralRe: Hiding the Property Bug & its Solution Pin
Bhasker Kandpal7-Nov-12 6:53
Bhasker Kandpal7-Nov-12 6:53 
GeneralThis doesn't work as expected Pin
zackp198320-Dec-10 12:06
zackp198320-Dec-10 12:06 
GeneralRe: This doesn't work as expected Pin
zackp198321-Dec-10 12:05
zackp198321-Dec-10 12:05 
GeneralRe: This doesn't work as expected Pin
Bhasker Kandpal21-Dec-10 19:06
Bhasker Kandpal21-Dec-10 19:06 
Questionused your code... Pin
Antonio Cella25-Feb-10 23:50
Antonio Cella25-Feb-10 23:50 
AnswerRe: used your code... Pin
Bhasker Kandpal12-Mar-10 18:19
Bhasker Kandpal12-Mar-10 18:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.