BLOG.CSHARPHELPER.COM: Use a PropertyGrid control to let the user edit program objects in C#
Use a PropertyGrid control to let the user edit program objects in C#
The PropertyGrid control is pretty amazing. Simply set its SelectedObject property to an object in your code 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 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 nicely.
class Person { private string _FirstName; public string FirstName { get { return _FirstName; } set { _FirstName = value; } }
The form's Load event handler makes an array of Person objects and sets the ListBox's DataSource property to the array so it displays them.
When the user clicks on a list entry, the program sets the PropertyGrid's SelectedObject property, but there's one catch. Suppose the user just finished changing a Person'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 following 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.
After refreshing the ListBox in this way, the program displays the newly selected object 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; }
Comments