Clearing A Single Texbox when clicked In C#?
How do i make it so that when a text box is clicke开发者_运维百科d the text that was originally in the text box ("Enter Text Here") is cleared and only the first time it is clicked?
Edit: Sorry, I'm using C#.
The most common way to achieve that is to handle the the textbox's focus event (depending on what framework you're using this will vary) and then test for the expected "tip string". If it's there, then you clear the textbox. If not, you leave it alone.
If you only want to show the "tip" once, then you can unsubscribe from the event after you've handled it.
Note that if you give us some more information about what technology you're using (WinForms/WPF/ASP.NET/MVC/jQuery/HTML5/etc.) then a more specific and possibly more robust approach may be possible.
Assuming its WinForms App, simply bind a handler for the GotFocus
or Click
event.
I wouldn't follow the suggestion of changing text in GotFocus event - it will cause problems during binding and is not elegant.
WinForms:
There is special technique to set this kind of tooltip for any standard Windows textbox. Declare this:
private const uint ECM_FIRST = 0x1500;
private const uint EM_SETCUEBANNER = ECM_FIRST + 1;
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, uint wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);
and then use:
private void SetWatermark(string watermarkText)
{
SendMessage(this.Handle, EM_SETCUEBANNER, 0, watermarkText);
}
HTML:
<input name="email" placeholder="Enter text here">
What you are trying to do is called "Watermarking" a Text-Box. There are a number of methods do to it:
1) use the MouseClick event on the textbox to remove the Default text.
2) use a ready available class to implement it like the one found here:
http://vidmar.net/weblog/archive/2008/11/05/watermarked-textbox-in-windows-forms-on-.net.aspx
You can find some more info in similar questions asked on Stackoverflow here are a few:
Watermark / hint text / placeholder TextBox in WPF
Watermark in System.Windows.Forms.TextBox
How to use watermark System.Windows.Forms.TextBox using C#?
Hope this was helpful.
Good Luck.
You can do the following:
- handle the focus event (Focus) and clear the text if it's the one set as "tip"
- handle the focus lost event (LostFocus) and if the textbox is empty add the "tip" back to the textbox
精彩评论