C# 文本框水印
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18497130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Watermark for Textbox
提问by Smith
My Program:Has one textbox only. I am writing code using C# Language.
我的程序:只有一个文本框。我正在使用 C# 语言编写代码。
My Aim:To display text/watermark in textbox: 'Please enter your name'. So, when user clicks on the textbox, the default text/watermark gets clear/deleted so that user can enter his name in the textbox.
我的目标:在文本框中显示文本/水印:“请输入您的姓名”。因此,当用户单击文本框时,默认文本/水印会被清除/删除,以便用户可以在文本框中输入他的姓名。
My problem:I tried various codes that are available online but none of them seem to work for me. So, I thought I should ask here for a simple code. I have found a code online but that doesn't seem to work:
我的问题:我尝试了各种在线可用的代码,但似乎没有一个对我有用。所以,我想我应该在这里要求一个简单的代码。我在网上找到了一个代码,但似乎不起作用:
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;
}
}
}
Error:
错误:
Error 1 'System.Windows.Forms.TextBox' does not contain a definition for 'Watermark' and no extension method 'Watermark' accepting a first argument of type 'System.Windows.Forms.TextBox' could be found (are you missing a using directive or an assembly reference?)
错误 1“System.Windows.Forms.TextBox”不包含“Watermark”的定义,并且找不到接受“System.Windows.Forms.TextBox”类型的第一个参数的扩展方法“Watermark”(您是否缺少使用指令或程序集引用?)
Please, if you have any other suggestions for what I am aiming for, I would really appreciate it. I tired many examples online but all are confusing/don't work. Thanks for your help in advance. :)
请,如果您对我的目标有任何其他建议,我将不胜感激。我在网上累了很多例子,但都令人困惑/不起作用。提前感谢您的帮助。:)
采纳答案by Jonesopolis
just tried this out. It seems to work fine in a new Windows Forms project.
刚试过这个。它似乎在新的 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;
}
}
}