Jeremy Holland
Jeremy Holland

Reputation: 21

Setting property default values for a Web User Control

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.

Upvotes: 1

Views: 1745

Answers (2)

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

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 property initializer, which were added in C# 6). If you're storing your stuff in the ViewState, you'll need to expand those property definitions and make them access the ViewState. Then set the default values for the properties in the OnInit method to avoid persisting them on the client side.

Upvotes: 3

bwarner
bwarner

Reputation: 872

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.

Upvotes: 0

Related Questions