开发者

Web user control set default value

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

public enum MessageType
{
    Good,
    Bad
}

publi开发者_运维技巧c 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜