views:

80

answers:

2

I am trying to build a web user control and set some default values for its properties in the code-behind like this:

[DefaultValue(typeof(int), "50")]
public int Height { get; set; }

[DefaultValue(typeof(string), "string.Empty")]
public string FamilyName { get; set; }

[DefaultValue(typeof(Color), "Orange")]
public System.Drawing.Color ForeColor { get; set; }

When I add the user control to the page and call it without any properties:

<uc1:Usercontrol ID="uc" runat="server" />

the default values are not set and every property is 0 or null.

What am I doing wrong?

Thanks.

+2  A: 

The DefaultValueAttribute will not set any value for your property, it only serves as a hint for designers and whatnot.

If you want a default value, you'll have to set it in the constructor (or even better, in a field initializer, which the shorthand property syntax unfortunately doesn't allow). If you're storing your stuff in the ViewState, you'll need to expand those property definitions and do it properly, returning the default value if it doesn't exist in the ViewState (never ever store the default in there)

Matti Virkkunen
A: 

From http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx

Note 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.

In other words, the DefaultValueAttribute just gives you a place to declare what you want the value to be. You still have to write code to populate the value from the attribute.

bwarner