Configure the PropertyGrid Control
July 20th, 2007 by Johan HiemstraExam objective: 70-526 - Configure the PropertyGrid component
The .NET Framework contains a fairly complete selection of controls and form components that allow information to be input, presented and changed in many different ways. In this article I will cover one of the more complex but also feature-rich components in the .NET framework: the PropertyGrid. Regardless of whether you have experience with the using the PropertyGrid in your own apps, if you used Visual Studio, you already used the PropertyGrid component many times. Visual Studio uses several PropertyGrid components in its main interface, the most obvious being the Properties and Events windows, highlighted in the screenshot below:
So setting the Properties of a Form or control for example is done by using a PropertyGrid and as you can see, it is very complete. It allows you to set a wide variety of Property types such as Booleans, Strings, Integers, Fonts, Point and Size structures, Colors, Images, Enums, and Collections without the need for complex code. Additionally, the PropertyGrid component can be extended to support additional custom property types and to customize the GUI of the properties in the PropertyGrid.
The PropertyGrid is particularly useful when you have a good amount of different properties that need to be set or displayed in the proper format. If you would use a combination of labels, textboxes, radio buttons, checkboxes, etc. you would have to create many different controls and write input validation code. That doesn’t mean a PropertyGrid is always a better alternative, a form with the classic form components works best for most applications as users are familiar with it.
Throughout the rest of this article we’re going to create an example project that shows you how little effort it takes to add a working PropertyGrid to a Form. After going over some basic properties of the PropertyGrid itself, we’ll cover its implementation in more detail. I assume you have some basic experience with Visual Studio and setting control properties using the GUI.
PropertyGrid Example Project
Start Visual Studio and start a new project with the name PropertyGridExample. The PropertyGrid is not listed in the Toolbox by default, so you need to add that first in the Choose Toolbox Items section (or Customize Toolbox), which you can reach from the Tools menu.

The PropertyGrid should now appear in the All Windows Forms section of the Toolbox.

Next, simply drag the PropertyGrid from the Toolbox to Form1 and scale it to fit the form. You may want to increase the size of the Form and the PropertyGrid a bit for a better look. Before PropertyGrid1 will display anything, you will need to set the SelectedObject property to an instance of an object. The object can be anything that has Properties, including forms, other controls, and custom classes. We’ll create our own custom class later on, first let’s see how easy it is to change properties of the SelectedObject at runtime by using a PropertyGrid.
Set the PropertyGrid1.SelectedObject to PropertyGrid1. This will make the PropertyGrid display its own properties and allows us to see how it influences the appearance of the control at runtime. You obviously won’t be able to use the PropertyGrid1 without building and running the project so press the Start Debugging button on the toolbar.
When Form1 opens PropertyGrid1 will read and display the properties of the object instance specified in the SelectedObject property, in this case PropertyGrid1 itself. If you change the value of a property it will take effect immediately. For example, change the Dock property to Fill. Remember, this changes the ‘instance’ of PropertyGrid1 and not the designer code of the PropertyGrid1 ‘object’. Whether you use the PropertyGrid for an existing control or a custom class, if you want to save the properties values you will need to use Setting, serialize the class or implement other means of saving the values.
The values displayed in the PropertyGrid are a snapshot and do not necessarily display the real value of the property. Set the SelectedObject property again at runtime or use the PropertyGrid1.Refresh() method to refresh the properties in the PropertyGrid. You need to do this if you change the properties displayed in the PropertyGrid by using something else than the PropertyGrid itself. Setting an option will also cause the PropertyGrid to refresh.
By default, the properties are sorted alphabetically and categorized. You can click the Alphabetical button for to remove the categories, or set the PropertySort property.

In many cases, a simple alphabetical order is the convenient for the user and then the toolbar of the PropertyGrid becomes rather useless (unless you want to use PropertyTabs). You can remove the toolbar by setting the ToolbarVisible property to False. Another area you may not need is the Help area. This is the section below the properties list describing the select property. You can remove the toolbar by setting the HelpVisible property to False. Yet another area is the Commands area and can be hidden by setting the CommandsVisibleIfAvailable property to False. In other words, this area will only be visible ‘if’ there are commands available. The commands appear as hyperlinks and can be used to allow users to perform common task on the PropertyGrid itself or any other object.
Besides the color of the text in the different sections of the PropertyGrid, it has several other properties that allow you to change its appearance. Some of the most noteworthy are BackColor, HelpBackColor, HelpForeColor, LineColor, and LargeButtons. It’s usually best to leave those values to the default and dock the PropertyGrid in a form, panel or other resizable container.
Now let’s see who the PropertyGrid works with a custom class with some different types of props. Choose Add Class from the Project menu and name the new class Employee.vb. Copy and paste the following code in the new class:
Public Class Employee Private _id As String Private _name As String Private _age As Integer Private _employed As Boolean Private _photo As Image Public Property ID() As Integer Get Return _id End Get Set(ByVal value As Integer) _id = value End Set End Property Public Property Name() As String Get Return _name End Get Set(ByVal value As String) _name = value End Set End Property Public Property Age() As Integer Get Return _age End Get Set(ByVal value As Integer) _age = value End Set End Property Public Property Employed() As Boolean Get Return _employed End Get Set(ByVal value As Boolean) _employed = value End Set End Property Public Property Photo() As Image Get Return _photo End Get Set(ByVal value As Image) _photo = value End Set End Property End Class
Add the following code to Form1:
Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ‘create a new instance of Employer Dim Employer1 As New Employer ’set the PropertyGrid1.SelectObject to Employer1 Me.PropertyGrid1.SelectedObject = Employer1 End Sub
Press the Start Debugging button again to run the project. The results should be similar to the following. (I set the PropertySort property to Alphabetical and ToolbarVisible to False.)
The power of the PropertyGrid immediately becomes clear in this example. If you try to change any of the properties, you will see they match the Property types of our Employee class. For example, the Employed property is a Boolean in the Employee class and therefore accepts only True or False, and the Photo property allows you to browse for and select an image from disk. Besides being user-friendly, the PropertyGrid validates the input and prevents users from assigning the wrong type of values to the underlying properties in the Employees class. Although the PropertyGrid would now be ready for use, there are several ways to customize the appearance of properties.
If we’d be working on a DataGridView or Listview for example, we would be able to change the appearance per column and row. For a PropertyGrid however, we need to change the underlying class (the one specified in the SelectedObject property) by applying attributes to the properties. These attributes are tags used to add metadata describing code elements. The PropertyGrid and other components that use reflection. Following are some of the most common attributes that apply to our example project.
- BrowsableAttribute – This attribute is synonymous with the Visible property that is common for many controls. I.o.w. it allows you to hide a property from the PropertyGrid.
- CategoryAttribute – By default, all properties are in the category Misc. You can specify a category for properties by using the CategoryAttribute.
- DescriptionAttribute – Allows you to specify a description that will be displayed in the Help section below the property list in the PropertyGrid, for the currently selected property.
- DefaultPropertyAttribute – This attribute should be added to the property that should get the focus when the PropertyGrid display the SelectedObject.
- DefaultValueAttribute – This attribute identifies the property’s default value.
- ReadOnlyAttribute – This attribute prevents users from editing the property’s value through the PropertyGrid. If the property itself is not declared as ReadOnly and has a Get and Set method, you can still edit the property through other means.
Following is an updated version of the Employee class that includes several of the above attributes. Copy and paste it over your Employee class code and run the project again to see the results.
Imports System.ComponentModel <DefaultPropertyAttribute(“ID”)> _ Public Class Employee Private _id As String Private _name As String Private _age As Integer Private _employed As Boolean Private _photo As Image <DescriptionAttribute(“This Employee’s ID”)> _ Public Property ID() As Integer Get Return _id End Get Set(ByVal value As Integer) _id = value End Set End Property <DescriptionAttribute(“This Employee’s full name”)> _ Public Property Name() As String Get Return _name End Get Set(ByVal value As String) _name = value End Set End Property <DescriptionAttribute(“This Employee’s age in years”), _ ReadOnlyAttribute(True)> _ Public Property Age() As Integer Get Return _age End Get Set(ByVal value As Integer) _age = value End Set End Property <DescriptionAttribute(“Is this Employee currently still employed?”), _ DefaultValueAttribute(True)> _ Public Property Employed() As Boolean Get Return _employed End Get Set(ByVal value As Boolean) _employed = value End Set End Property <BrowsableAttribute(False)> _ Public Property Photo() As Image Get Return _photo End Get Set(ByVal value As Image) _photo = value End Set End Property End Class
For practice, try adding other types of properties such as Font, Point, Color, or Enums to the Employees class. For properties with custom types, you can create your own dropdown boxes to display the property’s value. For example, you could create a dropdown with a PictureBox to display the Employee’s photo. You can read more about customizing the PropertyGrid control in Getting the Most Out of the .NET Framework PropertyGrid Control.
As I mentioned earlier, the PropertyGrid displays a snapshot of properties from any object instance including custom classes. Besides the possibility of making the PropertyGrid available to users of your application, I found it to be a handy debugging tool. Adding a temporary Form with a PropertyGrid, accessible through a short key combination or temporary button in your app, provides a convenient way for getting an overview of the values of properties of your custom classes at runtime. This way you can even correct values to continue debugging and prevent exceptions. And if you add a DropDownList to the form to change the SelectedObject property of the PropertyGrid, you can use a single PropertyGrid for multiple instances and for different objects.
| Views: 2,531 | Tags: .NET, MCTS, Visual Basic | Print This Post
|


