简体   繁体   中英

Custom Control Overridden Text Property Default Value

I have created a user control that has a textbox inside of it. I have overridden the Text property of the base control like the following:

    [Browsable(true)]
    [DefaultValue("")]
    [Description("Test1"), Category("Test")]
    public new string Text
    {
        get
        {
            return textBox1.Text;
        }
        set
        {
            textBox1.Text= value;
        }
    }

Now, I am having this issue where any instances i create of the control in a form, the Text always have a value of the controlname + number (of instance). I want to know why is this happening, and how to remove this default value? Thanks.

Initial hunch is that it is calling ToString() on the object. Override ToString() to return your desired value.

The attribute DefaultValue does not set the default value. The attribute is for describing what the default value is. You have to set the default value yourself, and then use the attribute to describe it.

So in your example, textbox1.Text must be populated with the control id. On your UserControl, in OnInit or wherever appropriate, you should call

this.Text = "";
[DefaultValue("")]
public override string Text
{
    get { return base.Text; }
    set
    {
        if (this.DesignMode && (Environment.StackTrace.Contains("System.Windows.Forms.Design.ControlDesigner.InitializeNewComponent")))
            return;
        base.Text = value; 
        Invalidate();
    }
}

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