title: Dynamically set readonly attribute of properties in a PropertyGrid
body: <p>I have a <code>PropertyGrid</code> that I used to display the properties in a helper class. I assign the helper class to the <code>PropertyGrid</code> like this:</p>
  
  <pre><code>myPropertyGrid.SelectedObject = mySettingsHelper;
  </code></pre>
  
  <p>In the helper class I assign the <code>ReadOnlyAttribute</code> at design time like this:</p>
  
  <pre><code>[DisplayName("DisplayExA"),
  Description("DescriptionExA"),
  ReadOnlyAttribute(true)]
  public string PropertyA { get; set; }
  
  [DisplayName("DisplayExB"),
  Description("DescriptionExB"),
  ReadOnlyAttribute(false)]
  public string PropertyB { get; set; }
  
  [DisplayName("DisplayExC"),
  Description("DescriptionExC"),
  ReadOnlyAttribute(true)]
  public string PropertyC { get; set; }
  </code></pre>
  
  <p>But now I need to be able to change this attribute on individual properties dynamically during runtime. Based on certain criteria some of these properties may need to be read-only or not read-only. How would I make the change dynamically at runtime?</p>
  
  <p><strong>EDIT:</strong> </p>
  
  <p>I tried the following code but this sets the ReadOnly attribute for every instance of the object! I want to do it per object. Sometimes one object might have PropertyA read-only while a second object has PropertyA to not be read-only.</p>
  
  <pre><code>public static class PropertyReadOnlyHelper
  {
      public static  void SetReadOnly(object container, string name, bool value)
      {
          try
          {
              PropertyDescriptor descriptor = TypeDescriptor.GetProperties(container.GetType())[name];
              ReadOnlyAttribute attribute = (ReadOnlyAttribute)descriptor.Attributes[typeof(ReadOnlyAttribute)];
              FieldInfo fieldToChange = attribute.GetType().GetField("isReadOnly",
                                                  System.Reflection.BindingFlags.NonPublic |
                                                  System.Reflection.BindingFlags.Instance);
              fieldToChange.SetValue(attribute, value);
          }
          catch { }
      }
  }
  </code></pre>