How to give an initial value to textBox?

2019-02-18 20:33发布

问题:

I want my C# program to have initial values for its textboxes. For example, in one of the textboxes, it should say "Please enter your name".

When you click (or tabStop) on the textbox, the initial value should disappear and the user will be able to enter their input to the textbox.

I can do all this with click_event, but using this method the initial text would not have less opacity. How am I able to achieve this?

回答1:

This is how I finally did it:

Boolean first_time_click = true;

private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.ForeColor = System.Drawing.Color.Gray;
            textBox1.Text = "Enter the Text";
        }

private void For_First_Click()
        {
            if (first_time_click)
            {
                textBox1.Clear();
                textBox1.ForeColor = textBox1.ForeColor = SystemColors.WindowText;
            }
            first_time_click = false;
        }

private void textBox1_Click(object sender, EventArgs e)
        {
            For_First_Click();
        }


回答2:

I assume you are talking about winform (tabstop) you have to handle it within the event key-press. you can use the below code:

TextBox1.Select(0, TextBox1.Text.Length);

this will select the text and window will remove it for you as soon as the user start to typing

you can use the same code to have this behavior also for TabStop



回答3:

All you need to do is set the Textbox's .Text property and use GotFocus event to clear the box when the person clicks (or tabs) into it to start typing.

Always remember that there are more ways than the mouse to navigate a form, so use the GotFocus event to determine when the user enters a control, and use the Validated event to determine when they've changed data and exited the control.



回答4:

For this type of effect you need java script.Because java script provide you functionality of mouse hover and mouse out these are the functions which provide you the same functionality which u seeing in this page of search bar. If you need code reply me i can give you.