如何在TextBox上显示提示文字
时间: 2024-06-06 11:07:48 浏览: 12
可以使用WatermarkTextBox控件,或者在代码中使用TextBox的GotFocus和LostFocus事件来实现。具体方法如下:
1. 使用WatermarkTextBox控件
WatermarkTextBox控件是一种自定义的TextBox控件,它可以在TextBox上显示提示文字。可以通过以下步骤使用WatermarkTextBox控件:
1)在Visual Studio中打开项目,右键单击项目,选择“管理NuGet程序包”。
2)在NuGet程序包管理器中搜索“WatermarkTextBox”,选择安装。
3)在窗体设计器中,将TextBox控件替换为WatermarkTextBox控件。
4)在属性窗口中设置WatermarkText属性为提示文字。
2. 使用GotFocus和LostFocus事件
在代码中使用GotFocus和LostFocus事件可以实现在TextBox上显示提示文字。具体方法如下:
1)在窗体加载事件中添加以下代码:
private void Form1_Load(object sender, EventArgs e)
{
textBox1.ForeColor = Color.Gray;
textBox1.Text = "请输入内容";
}
2)在TextBox的GotFocus事件中添加以下代码:
private void textBox1_GotFocus(object sender, EventArgs e)
{
if (textBox1.Text == "请输入内容")
{
textBox1.Text = "";
textBox1.ForeColor = Color.Black;
}
}
3)在TextBox的LostFocus事件中添加以下代码:
private void textBox1_LostFocus(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
textBox1.ForeColor = Color.Gray;
textBox1.Text = "请输入内容";
}
}
这样就可以在TextBox上显示提示文字了。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)