如何在文本框中灰显默认文本?

时间:2013-01-27 03:30:59

标签: c# c#-4.0 c#-3.0

当我点击文本框时,我希望默认文本消失。是否还有其他财产可以用于此目的?

3 个答案:

答案 0 :(得分:3)

将一个方法添加到TextBox的GotFocus事件中,该事件将Text属性更改为“”

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 = "";
}

答案 1 :(得分:2)

听起来你想要在文本框中添加水印。

请参阅这些文章。

答案 2 :(得分:2)

以下将以灰色设置默认文本。此外,当您将文本框保留为空白时,再次将默认文本设置为文本框。

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();
    }

enter image description here