Search code examples
asp.netconstructorweb-controls

is there a kind of property only set in a web control constructor?


I have a WebControl and it has a property. However, value of this property should not be changed once the control has been constructed... in other words, the property can be set only in some code like:

<ct:Acontrol ID="xxx" Aproperty="xxx"  runat="server"></ct:Acontrol>

but not:

xxx.Aproperty=...

so what is the normal way to do that? Thanks!


Solution

  • The properties that you are using in markup must be public properties with a public getter and setter. There is no special syntax for "only set this once".

    What you can do is check in the setter whether it was already set and if so, not set to the new value.

    private string _aProperty;
    
    public string Aproperty
    {
        get { return _aProperty;}
        set
        {
           if(_aProperty == null)
           {
              _aProperty = value;
           }
        }
    }