Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real Hint in TextBox Visual Studio C# [duplicate]

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?

like image 313
Jon Spalding Avatar asked Oct 22 '25 06:10

Jon Spalding


1 Answers

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

like image 126
Amen Jlili Avatar answered Oct 23 '25 19:10

Amen Jlili



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!