cedric conte

cedric conte

  • NA
  • 111
  • 0

How to modify the ReadOnly attribut value on a specific object instance

Dec 21 2010 10:23 AM

Hi folks,

Here, i'm trying to modify the ReadOnly attribut value on a specific object instance.

Below, the demo expose the issue. Actually, the application change every ReadOnly attributs from all objects with same type.

thx a lot in advance for your help,

Best regards,

Cedric

application demo.jpg

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ControlLibrary;
using System.Reflection;

namespace WindowsFormsMocking
{
    public partial class Form1 : Form
    {
        private ContactInfo contactInfo = null;

        public Form1()
        {
            InitializeComponent();
            contactInfo = new ContactInfo();
            contactInfo.ChildContact = new ContactInfo();
            propertyGrid1.SelectedObject = contactInfo;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ContactInfo.SetMobileEdit(contactInfo, "Mobile", false);
            propertyGrid1.Refresh();
        }
    }

    [TypeConverter(typeof(ExpandableObjectConverter))]
    public class ContactInfo
    {
        [ReadOnly(false)]
        [Category("Contact Info")]
        public string Mobile { get; set; }

        [Category("Contact Info")]
        public string Name { get; set; }

        [Category("Child contact Info")]
        public ContactInfo ChildContact { get; set; }

        static public void SetMobileEdit(object instance, string property, bool allowEdit)
        {
            PropertyDescriptor descriptor = TypeDescriptor.GetProperties(instance.GetType())[property];
            ReadOnlyAttribute attrib = (ReadOnlyAttribute)descriptor.Attributes[typeof(ReadOnlyAttribute)];
            FieldInfo isReadOnly = attrib.GetType().GetField("isReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);

            // the Mobile property becomes Readonly for both contactInfo and souContactInfo
            // unfortunatly, I'm not finding the way to modified only contactInfo instance
            isReadOnly.SetValue(attrib, !allowEdit);
            
        }
    }
}