C# Examples

Menu:


Read-only PropertyGrid [C#]

This example demonstrates how to implement a read only property grid.

The default PropertyGrid control provided by WinForms doesn't support a read-only functionality. You can only disable the default PropertyGrid by setting the Enable property to false, but then a user won't be able to fully inspect all the properties of the selected object. The way to go is to add the class-level ReadOnlyAttri­bute, which is provided by .NET, to the selected object.

The main problem is how to add and remove class-level ReadOnly attribute to an object at runtime.

This code shows how to add ReadOnlyAttribute at runtime.

[C#]
TypeDescriptor.AddAttributes(this.SelectedObject, new Attribute[] { new ReadOnlyAttribute(_readOnly) });

The following code shows how to implement ReadOnlyProper­tyGrid.

[C#]
public class ReadOnlyPropertyGrid : PropertyGrid
{
  private bool _readOnly;
  public bool ReadOnly
  {
    get { return _readOnly; }
    set
    {
      _readOnly = value;
      this.SetObjectAsReadOnly(this.SelectedObject, _readOnly);
    }
  }

  protected override void OnSelectedObjectsChanged(EventArgs e)
  {
    this.SetObjectAsReadOnly(this.SelectedObject, this._readOnly);
    base.OnSelectedObjectsChanged(e);
  }

  private void SetObjectAsReadOnly(object selectedObject, bool isReadOnly)
  {
    if (this.SelectedObject != null)
    {
      TypeDescriptor.AddAttributes(this.SelectedObject, new Attribute[] { new ReadOnlyAttribute(_readOnly) });
      this.Refresh();
    }
  }
}

Note: In the previous code we actually do not remove the ReadOnly attribute. If you want to remove the attribute, you have to store the TypeDescriptor­Provider and then use the RemoveProvider method as shows the following code.

[C#]
// store the provider
TypeDescriptionProvider provider = TypeDescriptor.AddAttributes(this.SelectedObject,
new Attribute[] { new ReadOnlyAttribute(_readOnly) });

// remove the provider
TypeDescriptor.RemoveProvider(provider, this.SelectedObject);

Note: The property grid in this example can inspect only classes which implements IComponent interface.


See also

By Franta Zahora, 08-Jun-2009