文本框的水印

我的程序:只有一个文本框。 我正在使用C#语言编写代码。

我的目标:在文本框中显示文字/水印:’请输入你的名字’。 因此,当用户点击文本框时,默认文本/水印会被清除/删除,以便用户可以在文本框中输入他的名字。

我的问题:我尝试了各种在线可用的代码,但它们似乎都不适合我。 所以,我想我应该在这里问一个简单的代码。 我在网上找到了一个代码,但似乎不起作用:

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); SetWatermark("Enter a text here..."); } private void SetWatermark(string watermark) { textBox1.Watermark = watermark; } } } 

错误:

错误1’System.Windows.Forms.TextBox’不包含’Watermark’的定义,并且没有扩展方法’Watermark’接受类型’System.Windows.Forms.TextBox’的第一个参数可以找到(你错过了吗?使用指令或程序集引用?)

如果您对我的目标有任何其他建议,我将非常感激。 我在网上累了很多例子,但都很混乱/不工作。 感谢您的帮助。 🙂

刚试了这个。 它似乎在新的Windows窗体项目中正常工作。

 public partial class Form1 : Form { public Form1() { InitializeComponent(); textBox1.ForeColor = SystemColors.GrayText; textBox1.Text = "Please Enter Your Name"; this.textBox1.Leave += new System.EventHandler(this.textBox1_Leave); this.textBox1.Enter += new System.EventHandler(this.textBox1_Enter); } private void textBox1_Leave(object sender, EventArgs e) { if (textBox1.Text.Length == 0) { textBox1.Text = "Please Enter Your Name"; textBox1.ForeColor = SystemColors.GrayText; } } private void textBox1_Enter(object sender, EventArgs e) { if (textBox1.Text == "Please Enter Your Name") { textBox1.Text = ""; textBox1.ForeColor = SystemColors.WindowText; } } }