WinForm Set default value for textbox (default value disappears after getting focus)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.