views:

830

answers:

2

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!

+1  A: 

Just set the desired default value, when declaring a variable:

class myControl
{
    private bool _showBox = true;

    [PersistenceMode(PersistenceMode.Attribute), DefaultValue(false)]
    public bool showBox
    {
        get { return _showBox; }
        set { _showBox = value; }
    }
}

Optional you can add the DefaultValueAttribute for designer.

Kamarey
+2  A: 

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 {
         if (_ShowBox == null) { 
             throw new Exception ("ShowBox must be setted.") 
         }

         return _ShowBox;
        }
}
Canavar
thank you! this is perfect
Jason