Use a PropertyGrid to let the user edit objects in C#


A program can use a PropertyGrid control to let the user edit the properties of objects defined by the program. Simply set the control’s SelectedObject property to an object and the user can view and edit that object’s properties.

This example displays a list of Person objects and lets the user edit the one that is selected. The Person class defines public FirstName, LastName, Street, City, State, Zip, Email, and Phone properties. (Note that the properties must be implemented as properties not as fields.)

The following code shows part of the Person class’s definition. Notice that it overrides the ToString method so the ListBox can display a Person easily.

class Person
    private string _FirstName;
    public string FirstName
            return _FirstName;
            _FirstName = value;


    public override string ToString()
        return FirstName + " " + LastName;

The form’s Load event handler makes an array of Person objects and sets the ListBox control’s DataSource property to the array so it displays them.

When you click on a Person in the ListBox, the following code displays the selected Person in the PropertyGrid.

// Display this person's properties in the PropertyGrid.
private void lstPeople_SelectedIndexChanged(
    object sender, EventArgs e)
    // Reset the DisplayMember to make
    // the ListBox refresh its list.
    lstPeople.DisplayMember = "FirstName";
    lstPeople.DisplayMember = null;

    // Display the selected Person in the PropertyGrid.
    pgdPeople.SelectedObject = lstPeople.SelectedItem;

The code needs to set the PropertyGrid‘s SelectedObject property, but there’s a catch. Suppose you just finished changing a Person object’s FirstName property. In that case, the ListBox is displaying the old value, so the program must update the ListBox to show the new value.

To update the ListBox, the code sets the ListBox‘s DisplayMember to “FirstName.” That tells the list to display each object’s FirstName property. It then resets DisplayMember to null so the list displays the objects using ToString, the default behavior. The result is that the ListBox refreshes its display.

After refreshing the ListBox in this way, the program displays the newly selected object in the PropertyGrid.

Download Example   Follow me on Twitter   RSS feed

This entry was posted in controls, OOP and tagged , , , , , , , . Bookmark the permalink.

2 Responses to Use a PropertyGrid to let the user edit objects in C#

  1. Pingback: Use PropertyGrid descriptions and categories in C# -

  2. Pingback: Use a type converter with a PropertyGrid control in C# -

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.