I can't seem to figure this out-
I have a single text box that has text in it. When I put the mouse in it and click it, I need the text to clear so new text can go in.
Does anyone have a sample?
TIA
I can't seem to figure this out-
I have a single text box that has text in it. When I put the mouse in it and click it, I need the text to clear so new text can go in.
Does anyone have a sample?
TIA
's MouseDown suggestion is a perfectly fine, minimal fix to clear a TextBox on click, and it answers the original request. For production use there are a few practical issues to consider: it won't fire when the user tabs into the box (keyboard accessibility), it will clear text on every click (risking accidental data loss), and it doesn't distinguish a placeholder string from user input.
A more robust, common pattern is a placeholder/watermark that is removed only when it matches the default text and restored on leave. The placeholder text can be stored in the control's Tag and shown in a dim color so users know it's not real input. Example (VB.NET, Windows Forms):
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Tag = "Enter name here"
TextBox1.Text = CStr(TextBox1.Tag)
TextBox1.ForeColor = Color.Gray
End Sub
Private Sub TextBox1_Enter(sender As Object, e As EventArgs) Handles TextBox1.Enter
Dim tb As TextBox = DirectCast(sender, TextBox)
If tb.Text = CStr(tb.Tag) Then
tb.Text = ""
tb.ForeColor = Color.Black
End If
tb.SelectAll()
End Sub
Private Sub TextBox1_Leave(sender As Object, e As EventArgs) Handles TextBox1.Leave
Dim tb As TextBox = DirectCast(sender, TextBox)
If String.IsNullOrWhiteSpace(tb.Text) Then
tb.Text = CStr(tb.Tag)
tb.ForeColor = Color.Gray
End If
End Sub Notes and tips: prefer the Enter event (keyboard-friendly) over MouseDown for accessibility; call SelectAll so typed input replaces the placeholder; store the placeholder in Tag so it is easy to change or localize; for a native-looking placeholder on recent Windows use the EM_SETCUEBANNER API (P/Invoke) or a third-party control. This approach avoids accidental clearing and preserves expected tab/keyboard behavior while keeping the UI clear for search-engine visitors who find this thread later.
Jump to Post— Luc001 77Hi,
You can do it like this:
Private Sub TextBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseDown TextBox1.Text = "" End Sub
Hi,
You can do it like this:
Private Sub TextBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseDown
TextBox1.Text = ""
End Sub Thanks a lot- that was pretty simple.
thanksssss
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.