Question

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!

Was it helpful?

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; }
}

OTHER TIPS

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.

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.

ReSharper recommends using an auto-property, and setting the default value in the constructor, like so:

public class MyControl
{
  public MyControl()
  {
    ShowBox = true;
  }

  public bool ShowBox { get; set; }
}  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top