I am auto-generating code that creates a winform dialog based on configuration (textboxes, dateTimePickers etc). The controls on these dialogs are populated from a saved da
I needed to use this for different classes, so I created this generic function:
public static bool IsPropertyReadOnly<T>(string PropertyName)
{
MemberInfo info = typeof(T).GetMember(PropertyName)[0];
ReadOnlyAttribute attribute = Attribute.GetCustomAttribute(info, typeof(ReadOnlyAttribute)) as ReadOnlyAttribute;
return (attribute != null && attribute.IsReadOnly);
}
With PropertyDescriptor, check IsReadOnly.
With PropertyInfo, check CanWrite (and CanRead, for that matter).
You may also want to check [ReadOnly(true)] in the case of PropertyInfo (but this is already handled with PropertyDescriptor):
ReadOnlyAttribute attrib = Attribute.GetCustomAttribute(prop,
typeof(ReadOnlyAttribute)) as ReadOnlyAttribute;
bool ro = !prop.CanWrite || (attrib != null && attrib.IsReadOnly);
IMO, PropertyDescriptor is a better model to use here; it will allow custom models.
I noticed that when using PropertyInfo, the CanWrite property is true even if the setter is private. This simple check worked for me:
bool IsReadOnly = prop.SetMethod == null || !prop.SetMethod.IsPublic;
Also - See Microsoft Page
using System.ComponentModel;
// Get the attributes for the property.
AttributeCollection attributes =
TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
// Check to see whether the value of the ReadOnlyAttribute is Yes.
if(attributes[typeof(ReadOnlyAttribute)].Equals(ReadOnlyAttribute.Yes)) {
// Insert code here.
}