Watermark for text box

My program: Has only one text box. I am writing code using C # language.

Purpose: To display the text / watermark in the text box: "Please enter your name." Thus, when the user clicks on the text field, the text / watermark is cleared / deleted by default, so the user can enter his name in the text field.

My problem: I have tried various codes available on the Internet, but none of them seem to work for me. So, I thought I should ask for simple code here. I found the code online, but this does not 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" that takes the first argument of the type "System.Windows.Forms.TextBox" can be found (you do not have the using directive or link to the assembly?)

Please, if you have any other suggestions regarding what I am striving for, I would really appreciate it. I am tired of many examples online, but everything is confusing / not working. Thank you in advance for your help.:)

+6
source share
1 answer

just tried it. It seems to be working fine in the new Windows Forms project.

 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; } } } 
+27
source

Source: https://habr.com/ru/post/952685/


All Articles