C# PropertyGrid: Windows Forms

Use the PropertyGrid control from Windows Forms to display properties from an object.

PropertyGrid. The PropertyGrid control in Windows Forms is an interesting widget. It uses reflection to display all of the properties on any object. You can change the properties. And they are reflected immediately in the user interface.

Info: The PropertyGrid looks the same as the property dialogs in Visual Studio.

Start. To get started, open your project and add a PropertyGrid by double-clicking on it in the Toolbox window. You can change the object whose properties are displayed in the PropertyGrid by assigning to the SelectedObject property.

Through reflection, the grid will enumerate all the property members on the object instance and display them. In the screenshot, I created a Button and assigned it to the SelectedObject property.

Then: I used Visual Studio to change the color of the Button in the grid and also the Text.

SelectedObject. The most important thing to do with the PropertyGrid is to set the SelectedObject property. You can do this not only in the Visual Studio designer, but at runtime in an event handler such as Form1_Load.

In this example, we create a Dictionary on the managed heap and then assign it as the SelectedObject. The screenshot reveals that we can then visually browse the Count, all the Keys, and all the Values of the Dictionary instance.

Example that uses PropertyGrid: C# using System; using System.Collections.Generic; using System.Windows.Forms; namespace WindowsFormsApplication15 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Create an example collection. var dictionary = new Dictionary<string, string>(); dictionary.Add("cat", "blue"); dictionary.Add("dog", "green"); // Assign SelectedObject. propertyGrid1.SelectedObject = dictionary; } } }

Discussion. Is the PropertyGrid useful in general Windows Forms programming? The PropertyGrid will always be technically-focused. It will display what it finds in the object through reflection.

Therefore: PropertyGrid is unsuitable for commonly-used interfaces or user-facing interfaces.

But: It could be useful for developing a settings window where advanced users can adjust certain settings in the program.

Not polished. The PropertyGrid will never have a highly polished and streamlined interface. But it can present a usable interface for when users might need to adjust the object model in a certain way.

Summary. The PropertyGrid control in Windows Forms provides a quick way to mutate the object model in your application through a prebuilt user interface. It is not as easy to use as a custom solution.

But: It is compatible with .NET programs and therefore useful when providing certain features such as options windows.

Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to