1

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?

1 Answers1

2

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
  • 1
    Note that setting `UseSystemPasswordChar` at run-time, the TextBox needs to recreate the Handle. It may have consequences. – Jimi Apr 07 '20 at 14:33
  • @Jimi Thanks for the tip :) I actually didn't know that. And it's not even mentioned in the docs. What kind of consequences do you think this might have though? – 41686d6564 stands w. Palestine Apr 07 '20 at 14:43
  • See code and notes (comments) in [RecreateHandleCore()](https://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/Control.cs,10947) and the reason why I posted that comment (on the question): [PasswordProtect](https://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/TextBox.cs,302) – Jimi Apr 07 '20 at 15:03