2

How to add a placeholder to a c# winform control?

When control lost focus and control text is null, I would like the placeholder to appear.

When textbox is UsePasswordChar true, It still shows the placeholder (in clear text), and when the user starts to write, it shows password characters.

Any idea?

Zuoanqh
  • 942
  • 4
  • 10
  • 26
Hassan Kotti
  • 31
  • 1
  • 2
  • Possible duplicate of [Adding placeholder text to textbox](https://stackoverflow.com/questions/11873378/adding-placeholder-text-to-textbox) – Fabio May 06 '18 at 05:50

3 Answers3

1

If you are using WinForms for .NET Core, or are planning on migrating in the future, you can use the new PlaceholderText property of the TextBox. It greatly simplifies things.

Placeholder

Password entry

VirtualValentin
  • 1,131
  • 1
  • 11
  • 19
0

I'm not very experienced with WinForms, but I would suspect you could use the GotFocus event to change the type to/from password based on whether the control has a value or not.

This should point you in the right direction: https://msdn.microsoft.com/en-us/library/system.windows.forms.control.gotfocus(v=vs.110).aspx

Scott Salyer
  • 2,165
  • 7
  • 45
  • 82
0

you can add events for lostFocus and AddFocus

Textbox myTxtbx = new Textbox();
myTxtbx.Text = "Enter text here...";

myTxtbx.GotFocus += GotFocus.EventHandle(RemoveText);
myTxtbx.LostFocus += LostFocus.EventHandle(AddText);

public void RemoveText(object sender, EventArgs e)
{
     myTxtbx.Text = "";
}

public void AddText(object sender, EventArgs e)
{
     if(String.IsNullOrWhiteSpace(myTxtbx.Text))
        myTxtbx.Text = "Enter text here...";
}

or you can create a new class with a hint, take a look at this answer here: Answer

Dor Lugasi-Gal
  • 1,430
  • 13
  • 35