0

I have a windows form with textfields. I would like that the textbox shows sample text and when i click on the textbox, the text is cleared. What is the best way to do this?

e.g. the form shows text: 192.18.130.44, as the user clicks on that textbox, the text is cleared.

michelle
  • 2,759
  • 4
  • 31
  • 46
  • 1
    Making a click event on the textbox, that clear the content. – provençal le breton Jun 21 '13 at 14:27
  • onClick Event TextBoxName.Text = "";? – Mark Jun 21 '13 at 14:28
  • I suggest you to use WaterMark Textboxs. here are some samples. [CueProvider](http://www.codeproject.com/Articles/27853/CueProvider) [WaterMark-TextBox-For-Desktop-Applications](http://www.codeproject.com/Articles/27849/WaterMark-TextBox-For-Desktop-Applications-Using-C) – JSJ Jun 21 '13 at 14:34

4 Answers4

2

Use the Enter event:

private void textBox_Enter(Object sender, EventArgs e)
{
    textBox.Text = null;
}

Although, unless you want it to always clear, I'd put some validation in there as well!

BTW...that link for CueProvider looks pretty slick, too, if you don't mind 3rd party stuff.

DonBoitnott
  • 10,787
  • 6
  • 49
  • 68
2

I think you want to show the default Text of a textbox, if it's just focused without any editing, the default Text will be restored when it loses focus like this:

string initText = "Love .NET";
bool edited;
//This code line is just for demonstrative purpose, it should be placed such as in the Form constructor
textBox1.Text = initText;
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    edited = !char.IsControl(e.KeyChar);
}

private void textBox1_Enter(object sender, EventArgs e)
{
    if(!edited) textBox1.Clear();
}

private void textBox1_Leave(object sender, EventArgs e)
{
    if (!edited) textBox1.Text = initText;
}

If you want to make the text look like watermark, you may want to apply more Font and ForeColor accordingly or some custom Paint if needed. The last is using a third-party textbox, it's up to you.

King King
  • 61,710
  • 16
  • 105
  • 130
  • +1 because it takes into account whether the user has edited the text because presumably when the user edits the text you don't want that to be cleared when they click off, then click back on. – Brad Rem Jun 21 '13 at 14:59
1

To make it show the sample text, set the text property in the properties menu to what you want, e.g. 192.18.120.44

To make it clear upon click, create a method for the click event and do txtbox1.Text = ""; You can initiate this method by double clicking the text box.

Mikkel Bang
  • 574
  • 2
  • 13
  • 27
0

When you load your winforms, check if the textbox is null or empty.

Then, if it is, show your sample text, and set a boolean to true(false if text is not empty).

Then, write a click event on you textBox, that cleared content if boolean is true and nothing if boolean is false, to avoid clear the textBox, if he contains other things that your sample..

provençal le breton
  • 1,428
  • 4
  • 26
  • 43