views:

24

answers:

3

When you add a label to the form from the toolbox, its text defaults to the item's name (label1, label2, etc). How can I make this happen with a custom control? So far, I have the following, which allows me to change the text through the property window:

private string _text;

[BrowsableAttribute(true)]
public override string Text
{
    get { return _text; }
    set
    {
        _text = value;
        lblID.Text = _text;
    }
}

Apparently the above code works as is, but I'm not sure why. Does Text default to the object's name automatically? The question still stands for other properties which don't override Text.

A: 
private string _text = "default value"
Femaref
A: 

Look into System.ComponentModel.DefaultValueAttribute

Matt Greer
Label's ability to do "label1", "label2" is handled through its designer. You can get info on that here: http://support.microsoft.com/kb/813808
Matt Greer
A: 

Apparently the Text property is automatically set to the objects name when you inherit from UserControl. The following code works:

public partial class CustomControl: UserControl
{
    public string Extension { get; set; }

    private string _text;

    [BrowsableAttribute(true)] // Initializes to "customControlN"
    public override string Text
    {
        get { return _text; }
        set { _text = value; }
    }
}
Daniel Rasmussen
That is because you are using the default Designer, which does that to the Text property. Almost all controls use the default Designer (or a subclass of it). If you disassemble the Label class you will see at the top: `Designer("System.Windows.Forms.Design.LabelDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")`, the LabelDesigner class subclasses `ControlDesigner`, it is ControlDesigner that is working with the Text property.
Matt Greer