Reputation:
I would like to toggle the password visibility of a textbox with a checkbox element. So whenever the state changes I would like to display the password with password characters or plain text.
Using C# I can simply assign a password character for asterisks via
textBox.PasswordChar = '*';
and for plain text
textBox.PasswordChar = '\0';
With VB I currently have this sample code
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked Then
TextBox1.PasswordChar = '\0'
CheckBox1.Text = "Hide password"
Else
TextBox1.PasswordChar = '*'
CheckBox1.Text = "Show password"
End If
End Sub
and found some information here
How do you declare a Char literal in Visual Basic .NET?
I know that '
is considered as a comment so I have to use double-quotes. I can update '*'
to "*"C
but what's the equivalent for '\0'
?
What is the correct way to unmask the textbox password?
Upvotes: 1
Views: 1568
Reputation: 19641
You may use the Nothing
keyword which will set the default value for the expected type (Char
in this case):
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
TextBox1.PasswordChar = If(CheckBox1.Checked, Nothing, "*"c)
End Sub
A better way would be to use the UseSystemPasswordChar
property instead of PasswordChar
. This makes the password mask look "more standard". That's, of course, unless you want to use a custom char. Here's an example:
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
TextBox1.UseSystemPasswordChar = Not CheckBox1.Checked
End Sub
Upvotes: 2