Mainly through the textbox to get focus enter and lose focus leave two events to achieve,
Ideas are as follows:
1. Set a string constant as the default value for the textbox;
2. Assign the default value to the textbox in the construction method of the interface, and set the ForeColor of the textbox to Gray;
3. Write the Get Focus event Textbox_enter (object sender, EventArgs e) to determine whether the TextBox text equals the default value,
Yes: Clears the contents of the TextBox and changes the foreground color to normal forecolor
4. Loss of focus event Textbox_leave (object sender, EventArgs e), determines whether the TextBox text is empty, and if empty, displays the default value again in gray
The specific code is as follows:
1 //default value for textbox2 Private ConstString Default_text ="Please enter your words.";3 //Construction Method4 PublicForm1 ()5 {6 //... Other Code7 8 //set the default and default foreground color (font color) for a textbox9 Setdefaulttext ();Ten } One A Private voidSetdefaulttext () - { -TextBox1.Text =Default_text; theTextbox1.forecolor =Color.gray; - } - - //Get focus Event Enter + Private voidTextBox1_Enter (Objectsender, EventArgs e) - { + if(TextBox1.Text = =default_text) A { atTextBox1.Text =""; -Textbox1.forecolor =Color.Black; - } - } - - //lost Focus Event Leave in Private voidTextbox1_leave (Objectsender, EventArgs e) - { to if(String.IsNullOrEmpty (TextBox1.Text)) + Setdefaultdesc (); -}
View Code
WinForm Sets a default value for the textbox (the default value disappears after getting focus)