文本框的水印

时间:2013-08-28 19:58:20

标签: c# visual-studio-2010

我的计划:只有一个文本框。我正在使用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'的第一个参数'(是你错过了使用指令或程序集引用?)

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

1 个答案:

答案 0 :(得分:28)

刚试了这个。它似乎在新的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;
        }
    }
}
相关问题