Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 971
None None Avatar asked Jan 21 '11 19:01

None None


3 Answers

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

like image 146
Aaron McIver Avatar answered Nov 07 '22 04:11

Aaron McIver


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 = "";
like image 3
s_hewitt Avatar answered Nov 07 '22 03:11

s_hewitt


[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();
    }
}
like image 2
Steave Avatar answered Nov 07 '22 02:11

Steave