Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 307
Jason Avatar asked May 04 '09 07:05

Jason


Video Answer


3 Answers

I know I'm late but I just wanted to mention that

[DefaultValue(false)]

will NOT set the attribute to false. See: http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx. It says:

"A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code."

This attribute is only to indicate in the Visual Studio Designer what you consider to be a default value. If someone using your control changes this value, it will be displayed bold to signal that this value is non-default.

like image 70
binford Avatar answered Sep 22 '22 14:09

binford


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; }
}
like image 38
Canavar Avatar answered Sep 22 '22 14:09

Canavar


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.

like image 30
Kamarey Avatar answered Sep 19 '22 14:09

Kamarey