[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

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

example

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 { get { return _FirstName; } set { _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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.