0

I am working on a Winforms project and I would like to create a Watermark in a TextBox. I tried a code that seems to be the right solution but is incorrect.

There is my code :

private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Text = "Veuillez entrez votre nom ici";

            if (textBox1.GotFocus)
            {
                textBox1.Text = "";
            }
        }

And I get this error at "GotFocus" :

CS0079 C# The event can only appear on the left hand side of += or -=

I searched on google but I didn't find any solutions to help my case.
What should I use instead of "GotFocus" to create a Watermark ?

Best regards, Zancrew.

Zancrew
  • 57
  • 6

1 Answers1

0

A lazy solution

create a label and locate it where you want your watermark to be shown and disable it then paste code below on textbox's textchanged event

label_watermark.Visible = textBox1.Text.Length<1;
trksyln
  • 136
  • 10
  • Read the linked duplicate post as it's not a good solution at all. – Reza Aghaei Dec 02 '19 at 11:01
  • what do you mean? – trksyln Dec 02 '19 at 11:07
  • There are two good ways to show a watermark, one and most reliable, sending [EM_SETCUEBANNER](https://learn.microsoft.com/en-us/windows/win32/controls/em-setcuebanner?WT.mc_id=DT-MVP-5003235) like what is done [here](https://stackoverflow.com/a/4902969/3110834), the other one which also works for multi-line text boxes and lets you to use different font and color is handling [WM_PAINT](https://learn.microsoft.com/en-us/windows/win32/gdi/wm-paint?WT.mc_id=DT-MVP-5003235) like what is done [here](https://stackoverflow.com/a/36534068/3110834). – Reza Aghaei Dec 02 '19 at 11:12
  • They say its not so reliable on comments also as i didn't say its good or better. its a simple and lazy way to do it. but thanks anyway good to know. – trksyln Dec 02 '19 at 11:37