Search code examples
asp.netuser-controlsdefault

UserControl Default Value in Property


I have a UserControl with a few boolean properties in it. I would like them to be set to true by default if not set explicitly in the .aspx page, or at least force them to be declared if there's no way to set a default. I know there is a way to do this because lots of controls have required properties that break your app when you try to run it and they're not declared.

How do I do this?

Example:

<je:myControl runat="server" id="myControl" showBox="False">

I want the system to either break or set the default to "true" if showBox is left out of this declaration.

Thanks!


Solution

  • Define your properties with their default values like that :

    private bool _ShowBox = false;
    public bool ShowBox
    {
        set { _ShowBox = value; }
    }
    

    or in your control's constructor, set default values :

    public MyControl()
    {
        _ShowBox = false;
    }
    

    or throw exception if it's not assigned :

    private bool _ShowBox = false;
    public bool ShowBox
    {
        set { _ShowBox = value; }
        get { return _ShowBox; }
    }