Click on a textbox and clear it's contents.
Hi everyone. I am working on a student program, and basically I have a textbox called Text1 that says CLICK HERE TO ENTER ANSWER, but when the student clicks on it, I would like to clear the contents of the box.
I have googled it, and found code to erase it in VB.Net, but was wondering if anyone knew how to do the same, but in VB6?
Here is the VB.net code I found.
Private Sub TextBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseDown
TextBox1.Text = ""
End Sub
I know there is a MouseDown event, but the "handles"?
:) Thanks a lot!
Re: Click on a textbox and clear it's contents.
No handles. Just double-click on the textbox to open the code-window, and then choose the mousedown-event from the combobox of events. The IDE should give you now the skeleton of the procedure where you just type in
Text1.text=""
Re: Click on a textbox and clear it's contents.
I suggest to use the GotFocus event, instead, because if user navigate to TextBox using the TAB key then the MouseDown event will not fire.
Re: Click on a textbox and clear it's contents.
As pointed by gibra, here's how you would typically do it:
Code:
Private Sub Text1_GotFocus()
If Text1 = "CLICK HERE TO ENTER ANSWER" Then Text1 = vbNullString
End Sub
Private Sub Text1_LostFocus()
If LenB(Text1) = 0& Then Text1 = "CLICK HERE TO ENTER ANSWER"
End Sub
Re: Click on a textbox and clear it's contents.
True. Haven't thought of that. The same if the user has entered some text into the textbox and then clicks somewhere else in the textbox to correct something it would erase all text already entered.
Re: Click on a textbox and clear it's contents.
On LostFocus if prefer to use Trim() instead of LenB() because if use press spacebar textbox seems empty, but don't.
Also, if there are many textbox which we use a 'default' text, then I suggest to use Tag property to store the 'default' text.
Alternately, if the 'default' text is the same for more TextBoxs then we can use a variable.
Code:
Private Sub Form_Load()
Text1.Tag = "CLICK HERE TO ENTER ANSWER"
Text1.Text = Text1.Tag
End Sub
Private Sub Text1_GotFocus()
If Text1.Text = Text1.Tag Then
Text1.Text = vbNullString
End If
End Sub
Private Sub Text1_LostFocus()
If Trim(Text1) = vbNullString Then Text1 = Text1.Tag
End Sub