Search code examples
c#user-controlsdefault-valuecustom-properties

How do I set a default value for a ASPX UserControl property?


I have a user control defined on an page as follows:

<uc:MyUserControl ID="MyUserControl" runat="server" Visible="true" />

I am wanting to reuse the same control on a different page with a custom property as follows:

<uc:MyUserControl ID="MyUserControl" runat="server" Visible="true" 
MyCustomProperty="MyCustomText" />

The purpose of MyCustomProperty is to control some text in MyUserControl to be whatever I specify it to be.

For the first case I want the text to be "View" and for the second case I want it to be "MyCustomText".

In my user control I have the following code to define the property:

[DefaultValue("View")]
public string MyCustomProperty { get; set; }

I also have the following code to update the text based on the property:

LinkButton buttonSelect = e.Item.FindControl("ButtonSelect") as LinkButton;
if(buttonSelect != null) buttonSelect.Text = MyCustomProperty;

What actually happens is that when the custom property isn't supplied in the first case then MyCustomProperty == null.

I've tried to specify that the default should be "View" by adding the DefaultValue attribute but it hasn't had the affect that I intended.

Can anyone spot what I'm doing wrong?


Solution

  • The DefaultValueAttribute is used by visual designers and code generators to identify the default value, so they can more intelligently generate code. In Visual Studio, this attribute will cause a property to be shown in bold when the property returns a value that differs from the value declared in the attribute.

    DefaultValueAttribute does not actually set the default value of the property for you. To do this, simply specify a suitable default value in your constructor. In your case:

    public partial class MyUserControl
    {
        public MyUserControl()
        {
            MyCustomProperty = "View";
        }
    
        ...
    }
    

    Also, be aware that the property as you have coded it will not survive Postbacks. If this is important behaviour between round trips, be sure to add it to view state!