How do I implement a TextBox that displays “Type h

2019-01-17 09:43发布

Displaying "Type here to ..." until the user enters text into a TextBox is a well-known usability feature nowadays. How would one implement this feature in C#?

My idea is to override OnTextChanged, but the logic to handle the changes of text from and to "Type here" is a bit tricky...

Displaying "Type here" on initialization and removing it on first input is easy, but I want to display the message every time the entered text becomes empty.

16条回答
冷血范
2楼-- · 2019-01-17 10:41

Handle the lost focus event and if the property Text is empty, fill it with your default string.

查看更多
Fickle 薄情
3楼-- · 2019-01-17 10:41

In the last version of C# the TextBox has the property PlaceholderText, which does all work. So you only need to set "Type here..." as value of this property.

查看更多
等我变得足够好
4楼-- · 2019-01-17 10:43

Displaying "Type here to ..." until the user enters text into a TextBox is a well-known usability feature nowadays. How would one implement this feature in C#?

  1. Set textbox.text as "Type here to ..."

  2. create an event, say box_click()

  3. -->Put this code in your method

    private void box_Click(object sender, EventArgs e)
    {
        Textbox b = (Textbox)sender;
        b.Text = null;
    }
    
  4. now assign this method to the "Enter" event of your textbox(maybe one or many)

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-17 10:44

PRODUCES SIMILAR OUTPUT TO HTML WATERMARK

Here is my code for textbox "watermark" or "preview" text - works great! Using Windows Forms Application.

NOTE: This example has 3 text boxes, each has the below method for the "mouse leave" event, and "mouse enter" event respectively.

private void textBoxFav_Leave(object sender, EventArgs e) {
  TextBox textbox = (TextBox)sender;
  if (String.IsNullOrWhiteSpace(textbox.Text)) {
    textbox.ForeColor = Color.Gray;
    if (textbox.Name == "textBoxFavFood") {
      textbox.Text = "Favorite Food";
    }
    else if (textbox.Name == "textBoxFavDrink") {
      textbox.Text = "Favorite Drink";
    }
    else if (textbox.Name == "textBoxFavDesert") {
      textbox.Text = "Favorite Desert";
    }
  }
  else {
    textbox.ForeColor = Color.Black;
  }
}

private void textBoxFav_Enter(object sender, EventArgs e) {
  TextBox textbox = (TextBox)sender;
  if (textbox.Text == "Favorite Food" || textbox.Text == "Favorite Drink" || textbox.Text == "Favorite Desert") {
    textbox.Text = "";
    textbox.ForeColor = Color.Black;
  }
}
查看更多
登录 后发表回答