0

I created custom control PlaceHolderTextBox with some properties. Here is my code:

class PlaceHolderTextBox:TextBox
{
    public string PlaceHolderText { get; set; }
    public Color PlaceHolderColor { get; set; }
    public Font PlaceHolderFont   { get; set; }
    public Color StandardColor    { get; set; }
    public PlaceHolderTextBox()
    {
        GotFocus    += OnGetFocus;
        LostFocus   += OnLostFocus;
        TextChanged += OnTextChanged;

        Text      = PlaceHolderText;
        ForeColor = PlaceHolderColor;
        Font      = PlaceHolderFont;

    }
    private void OnGetFocus(object sender,EventArgs e)
    {
        if (this.Text == this.PlaceHolderText)
        {
            ForeColor = StandardColor;
            Text = "";
        }
    }
    private void OnLostFocus(object sender, EventArgs e)
    {
        if (this.Text == "")
        {
            ForeColor = PlaceHolderColor;
            Text = PlaceHolderText;
        }
    }
}


In designer, i set values:
image

And when i start program, i get empty textbox.
I think reason of that behaviour is that on time constructor executes, the properties are empty, but im not sure.
Also, i want to make events when i change these custom properties.
Is that possible?

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42

1 Answers1

0

Let's first focus on the problem which you are facing. But make sure that you read the Note.

Here is the problem → In constructor, you have set text to the value of PlaceHolderText property. At that time, PlaceHolderText is empty.

Even if you set a default hard-coded value for Text property in constructor, when you drop an instance of your custom textbox on the form, the InitializeNewComponent method of the TextBoxDesigner will set the Text property to empty string. If you close and reopen the designer, your text will appear.

Note - Why you should not show a placeholder text by setting Text property

It's definitely not a good idea to implement placeholder feature by setting and resetting Text property in GotFocus/LostFocus or Enter/Leave events, because:

  • It will have problems when using data-binding, it will raise validation errors when binding to a number or date property or properties which should be in a specific format.
  • When data-binding, if you press Save button, placeholder values will be saved in database unwantedly.
  • Based on your code, if user types the same value as you set for placeholder, then when losing focus, you are resetting it to empty. It's wrong.

To have a placeholder(also known as hint, watermark and cue-banner) you can use one of the following solutions: the native text box feature or a custom paint solution.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398