Boardy Boardy - 3 months ago 57
C# Question

Adding placeholder text to textbox

I am looking for a way to add placeholder text to a textbox like you can with a textbox in html5.

I.e. if the textbox has no text, then it adds the text

Enter some text here
, when the user clicks on it the placeholder text disappears and allows the user to enter their own text, and if the textbox loses focus and there is still no text then the placeholder is added back to the textbox.

Answer

Wouldn't that just be something like this:

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

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

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

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

Thats just pseudocode but the concept is there.

Comments