简体   繁体   中英

How to enable overwrite text in a textbox?

I'm making a program which requires a login system. What I want to do is have a textbox which contains the word 'Username' and when the user clicks it, the 'Username' text is overwritten. For example, Spotify use it on their login screen:

在此处输入图片说明

My question is, how do I do this?

Set the Text property of the TextBox that you are using for the username to the string "Username" . Then, in the TextBox 's Click event, change it to a blank string. Like so:

Private Sub TextBox1_Click(sender As Object, e As EventArgs) Handles TextBox1.Click
    TextBox1.Text = ""
End Sub 

Edit: As @LarsTech mentioned, this does not address if the user tabs into the TextBox . If you wanted to account for that too, use the TextBox 's Enter event instead:

Private Sub TextBox1_Enter(sender As Object, e As EventArgs) Handles TextBox1.Enter
    TextBox1.Text = ""
End Sub

I agree, using Textbox1.Enter is the easiest solution. On top you can also catch the case of no text entered via TextBox1.Leave like that

Private Sub TextBoxLeaveHandle() Handles TextBox1.Leave
    If TextBox1.Text = "" Then
        TextBox1.Text = "Username"
    End If
End Sub

Sometimes it can also be useful to use the TextBox.SelectAll() function as it not immediately remove the entire text but (obviously from the name) select the entire text so you can overwrite it with your first keypress.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM