简体   繁体   中英

Web user control set default value

How can I set the default value of Text to be "abc"?

public enum MessageType
{
    Good,
    Bad
}

public partial class Message : System.Web.UI.UserControl
{
    public bool Visible { get; set; }       // Is the error visible
    public string Text { get; set; }        // Text of the error message
    public MessageType Type { get; set; }   // Message type

    protected void Page_Load(object sender, EventArgs e)
    {
        ErrorPanel.Visible = this.Visible;
        ErrorMsg.Text = this.Text;

        // Hide if nothing to display
        if (this.Text == null)
                this.Visible = false;

        // Set correct CSS class
        if (this.Type == MessageType.Good)
            ErrorPanel.CssClass = "good-box";
        else
            ErrorPanel.CssClass = "bad-box";
    }
}

Maybe you can use the old-school of declaring properties

private string _Text = "abc";

public string Text
{
   get { return _Text; }
   set { _Text = value; }
}

You could add a DefaultValue attribute to the Property?

eg:

[System.ComponentModel.DefaultValue( "abc" )]
public string Text {get;set;}

I believe the best place to do it would be in the constructor of the class

OR

private string _Text;    
public string Text
{
   get { return _Text ?? "Your Default"; }
   set { _Text = value; }
}

EDIT

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.

From MSDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM