Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watermark for Textbox [duplicate]

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. :)

like image 885
Smith Avatar asked Aug 28 '13 19:08

Smith


1 Answers

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;
        }
    }
}
like image 162
Jonesopolis Avatar answered Nov 18 '22 02:11

Jonesopolis