Share via


How to set placeholder text to textbox in C#

Question

Tuesday, March 22, 2016 7:29 AM

if the textbox has no text, then it adds the text Enter some text here, when the user clicks on it the placeholder text disappears and allows the user to enter their own text, and if the textbox loses focus and there is still no text then the placeholder is added back to the textbox.

All replies (1)

Tuesday, March 22, 2016 9:17 AM âś…Answered | 5 votes

Hi Danish,

You could try using the below code. Hope this helps you.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace PlaceHolderTbox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void textBox1_Enter(object sender, EventArgs e)
        {
            if(textBox1.Text=="Enter some text here")
            {
                textBox1.Text = "";
            }
        }

        private void textBox1_Leave(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                textBox1.Text = "Enter some text here";
                textBox1.ForeColor = Color.Gray;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Text = "Enter some text here";
        }
    }
}

Thanks,

Sabah Shariq