mezoid
mezoid

Reputation: 28710

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?

Upvotes: 3

Views: 2591

Answers (3)

Jakob Gade
Jakob Gade

Reputation: 12419

How about setting the property value explicitly rather than using the DefaultValue attribute?

private string _MyCustomProperty = "View";
public string MyCustomProperty 
{
  get
  {
    return _MyCustomProperty;
  }
  set
  {
    _MyCustomProperty = value;
  }
}

Upvotes: 2

Kirtan
Kirtan

Reputation: 21695

If you take a look at the note given in MSDN about DefaultValue, you'll understand what you are doing wrong -

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.

Upvotes: 1

Paul Turner
Paul Turner

Reputation: 39625

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!

Upvotes: 5

Related Questions