My Program: Has one textbox only. I am writing code using C# Language.
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?)
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. :)
just tried this out. It seems to work fine in a 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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With