How to set default value for ASPX UserControl property?

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

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

I want to reuse the same control on another 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 who I define it.

In the first case, I want the text to be “View”, and in the second case, I want it to be “MyCustomText”.

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

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

I also have the following code for updating text based on a property:

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

What actually happens is that when a custom property is not specified in the first case, MyCustomProperty == null.

, "", DefaultValue, , .

- , ?

+3
3

DefaultValueAttribute , . Visual Studio , , , , .

DefaultValueAttribute . . :

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

    ...
}

, , , , Postbacks. , !

+5

, DefaultValue?

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

, MSDN, DefaultValue, , -

A DefaultValueAttribute . .

+1

Source: https://habr.com/ru/post/1714944/


All Articles