Search code examples
c#winformstextboxwindows-forms-designer

Real Hint in TextBox Visual Studio C#


I'm currently making a Windows Forms Application on Visual Studio in C# and I'm trying to find a way to have a real hint.

I've found a lot of answers online on how to have some text preset there, Some examples even show how to grey out the text to look like a placeholder, but that's not what I'm looking for.

I want a grayed out text that you don't have to backspace to type something there. So I want it to behave like an HTML placeholder like the "Search Q&A" search bar on stack Overflow.

Is there an easy way to do this, like configuring a property of the textbox in the designer on Visual Studio?


Solution

  • This might be the ugliest code but I think you can improve it.

    This following class is merely an extension of the standard TextBox

     class PHTextBox : System.Windows.Forms.TextBox
        {
            System.Drawing.Color DefaultColor; 
            public string PlaceHolderText {get;set;}
            public PHTextBox(string placeholdertext)
            {
                // get default color of text
               DefaultColor = this.ForeColor;
                // Add event handler for when the control gets focus
                this.GotFocus += (object sender, EventArgs e) => 
                {
                    this.Text = String.Empty;
                    this.ForeColor = DefaultColor;
                };
    
                // add event handling when focus is lost
                this.LostFocus += (Object sender, EventArgs e) => {
                    if (String.IsNullOrEmpty(this.Text) || this.Text == PlaceHolderText)
                    {
                        this.ForeColor = System.Drawing.Color.Gray;
                        this.Text = PlaceHolderText;
                    }
                    else
                    {
                        this.ForeColor = DefaultColor;
                    }
                };
    
    
    
                if (!string.IsNullOrEmpty(placeholdertext))
                {
                    // change style   
                    this.ForeColor = System.Drawing.Color.Gray;
                    // Add text
                    PlaceHolderText = placeholdertext;
                    this.Text = placeholdertext;
                }
    
    
    
            }
    
    
        }
    

    Copy/paste to new cs file entitled PHTextBox.cs.

    Go to your graphic designer and add a TextBox. Go to the designer and change the instiantion line for the textbox as follow:

    enter image description here

    Now compile but before you do, just make sure the textbox is not the first element to get the focus. Add button for that matter.

    enter image description here