views:

378

answers:

3

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?

+3  A: 

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!

Programming Hero
In my case Postbacks are not an issue so your answer was just what I needed. I really should have looked up DefaultValue on MSDN but I was busy with so many other things that it didn't cross my mind...which is silly I know... thanks heaps for your help!
mezoid
+1  A: 

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.

Kirtan
+1  A: 

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