c# textbox使用
时间: 2023-10-28 12:58:56 浏览: 92
在C#中,你可以使用TextBox控件的属性来设置提示文字。具体的属性是WatermarkText。
下面是一个示例代码:
```csharp
using System;
using System.Windows.Forms;
namespace TextBoxWatermarkExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
textBox1.WatermarkText = "请输入文本";
}
}
public class TextBoxWithWatermark : TextBox
{
private string watermarkText;
public TextBoxWithWatermark()
{
this.GotFocus += TextBoxWithWatermark_GotFocus;
this.LostFocus += TextBoxWithWatermark_LostFocus;
}
public string WatermarkText
{
get { return watermarkText; }
set
{
watermarkText = value;
this.Text = watermarkText;
this.ForeColor = SystemColors.GrayText;
}
}
private void TextBoxWithWatermark_GotFocus(object sender, EventArgs e)
{
if (this.Text == watermarkText)
{
this.Text = "";
this.ForeColor = SystemColors.WindowText;
}
}
private void TextBoxWithWatermark_LostFocus(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.Text))
{
this.Text = watermarkText;
this.ForeColor = SystemColors.GrayText;
}
}
}
}
```
在这个示例中,我们创建了一个自定义的TextBox控件 TextBoxWithWatermark,它具有一个WatermarkText属性。
阅读全文