When I click on a textbox, I want the default text to disappear. Is there any other property that would work for this purpose?
Asked
Active
Viewed 2.6k times
3 Answers
4
The following Will set Default text in Gray color. Also When you leave the textbox as blank, again set default text to the textbox.
private void Form1_Load(object sender, EventArgs e)
{
this.textBox2.Enter += new EventHandler(textBox2_Enter);
this.textBox2.Leave += new EventHandler(textBox2_Leave);
textBox2_SetText();
}
protected void textBox2_SetText()
{
this.textBox2.Text = "Default Text...";
textBox2.ForeColor = Color.Gray;
}
private void textBox2_Enter(object sender, EventArgs e)
{
if (textBox2.ForeColor == Color.Black)
return;
textBox2.Text = "";
textBox2.ForeColor = Color.Black;
}
private void textBox2_Leave(object sender, EventArgs e)
{
if (textBox2.Text.Trim() == "")
textBox2_SetText();
}

SUHAIL AG
- 195
- 1
- 8
3
Add a method to the GotFocus
event of the TextBox that will change the Text property to ""
private void Form1_Load(object sender, EventArgs e) {
this.textBox1.GotFocus += new EventHandler(textBox1_Focus);
this.textBox1.Text = "some default text...";
}
protected void textBox1_Focus(Object sender, EventArgs e) {
textBox1.Text = "";
}

Erik Humphrey
- 345
- 5
- 18

Mortalus
- 10,574
- 11
- 67
- 117
-
-
Where should I put the default text name in above piece of code? When I click the textbox default text should disappear? – Kingsters Jan 27 '13 at 03:43
-
See my edit, just place it on the form load. NOTE that there are more sophisticated ways to accomplish that but I belie that this will be sufficient for you... – Mortalus Jan 27 '13 at 03:49
2
It sounds like you are wanting a Watermark in your Textbox.
See these articles.
- http://www.codeproject.com/Articles/319910/Custom-TextBox-with-watermark
- Watermark in System.Windows.Forms.TextBox
- and if you are using wpf something like this http://msdn.microsoft.com/en-us/library/bb613590.aspx