2

Is it possible to apply EditableAttribute at runtime? I want to make some properties editable only when the user has some role. Unfortunately EdiatbleAttribute is sealed. I can try to apply it at runtime by reflection but maybe there's more proper way to do this. Thanks for any advices.

Best regards

krlm
  • 817
  • 7
  • 18
  • 1
    Note: you can't change attributes via reflection. You *can* do this using the `System.ComponentModel`, but that only works if the caller is *asking* via `System.ComponentModel`. Unfortunately *at the property level* (rather than the type level) it is hard work to do it, and I think it is unlikely that it will achieve anything in this scenario (I suspect the caller is querying via reflection) – Marc Gravell May 27 '11 at 08:24

2 Answers2

1

There is a hack available at: How to Set Attribute Value at Runtime-- and How to Work around a Silly Bug

private void SetPropertyGrid() 
{ 
     PropertyDescriptor descriptor = TypeDescriptor.GetProperties(typeof(Student))["Address"];
     ReadOnlyAttribute attrib = (ReadOnlyAttribute)descriptor.Attributes[typeof(ReadOnlyAttribute)];
     FieldInfo isReadOnly = attrib.GetType().GetField("isReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
        isReadOnly.SetValue(attrib,true);

     propertyGrid1.SelectedObject = new Student();  
}

I was able to this code to change the ReadOnly attribute value of the property. The statement propertyGrid1.SelectedObject = new Student(); can be replaced by propertyGrid1.SelectedObject = myStudent i.e. you can modify the properties of an existing object.

Also, have a look at a similar question: Change Attribute's parameter at runtime

Community
  • 1
  • 1
Devendra D. Chavan
  • 8,871
  • 4
  • 31
  • 35
0

I think a good option is to create an extension helper for the control you need to use (TextBox etc) and if the IsReadOnly property is true (Editable(false)) then generate a disabled textbox.

Massimiliano Peluso
  • 26,379
  • 6
  • 61
  • 70