Search code examples
c#winformsuser-controlsdatagridviewcolumn

The property of user control always be false in C#?


I create a custom User Control which inherits from DataGridViewColumn.

Moreover, I added some properties in the control, but I can't modify them in design-time.

Even I set the default value as true, it's still false.

code:

public class ParaGridViewColumn : DataGridViewColumn
{                
    private bool _Necessary;
    private bool _ReadOnlyEmpty;

    [Description("Default cell status."), Category("Behavior"), DefaultValue(false)]
    public bool Necessary { get { return _Necessary; } set { _Necessary = value;} }                        
    [Description("When ReadOnly is true, clear value on the cell or not."), Category("Behavior"), DefaultValue(true)]
    public bool ReadOnlyEmpty { get { return _ReadOnlyEmpty; } set { _ReadOnlyEmpty = value; }}        
  
    public ParaGridViewColumn()
    {
        this.CellTemplate = new ParaGridViewCell();
    }
}

The new properties can shown on the window, but their default value are false.

I change them to true, entering and opening this window again, it's still false.

However, I can modify other properties regularly. It means I didn't lock this control. enter image description here

Why is that? Did I make something wrong?

Thanks a lot.


Solution

  • The first problem is with [DefaultValue(true)] for ReadOnlyEmpty while not setting the true value for it.

    You have not set the default value for property to true. In fact [DefaultValue(true)] help to CodeDomeSerizalizer to serialize value for this property if the property value is not equals to this default value. You should set ReadOnlyEmpty= true in constructor or _ReadOnlyEmpty instead.

    private bool _ReadOnlyEmpty=true;
    

    The problem here is when you set property to true in property grid, when closing the form, serializer will not serialize true value, because you said it is default but you have not set it to true, so it will remain false.

    The second problem is that if you want values persist, you should override Clone of base class and provide a clone copy that contains your custom properties.

    public override object Clone()
    {
        ParaGridViewColumn column = (ParaGridViewColumn)base.Clone();
        //Uncomment if you have ParaGridViewCell
        //column.CellTemplate = (ParaGridViewCell)CellTemplate.Clone();
        column.Necessary  = this.Necessary;
        column.ReadOnlyEmpty = this.ReadOnlyEmpty;
        return column;
    }