Friday, February 26, 2010

Password Character usage in TextBox

So you already recognized the new Windows feature for showing the password of a WLAN? A student asked me, how to do that. So here is the tutorial. “How to set and reset a password character in a textbox via C#”

password

So this is the screen hiding the Password by a Password Character. The Picture below shows you the same with unhidden Password.

passwordshow

The question is how did they do that. So let’s start with a quick tutorial.

I created a new Windows Form Project. And put a Textbox named “txtPassword” and a Checkbox with the name “checkPassword”. So the solution should look like this.

pwform

Switch to the Code Window. I like to create a Method to initialize Controls. So this is how this should look like.

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            InitializeControls();
        }

        private void InitializeControls()
        {
            checkPassword.Checked = false;
            txtPassword.PasswordChar = '●';
        }
    }

So how do you get the character for the Textbox? In Windows you can find the Character Map by Windows –> All Programs –> Accessories –> System Tools –> Character Map.

charmap

Select the character you want. Copy it and set the Textbox PasswordChar Property to that character. The next step is to create a new Event Handler for the checkbox CheckedChange event. The code should look like this.

        private void checkPassword_CheckedChanged(object sender, EventArgs e)
        {
            txtPassword.PasswordChar = checkPassword.Checked ? '\0' : '●';
        }

The idea of resetting the character map is to use the empty character symbol which is presented by ‘/0’. You recognized that i like to use the conditional operator instead of the if-else. Immo would say: “Why did you that way, because you can?” The if else way would look like this.

        private void checkPassword_CheckedChanged(object sender, EventArgs e)
        {
            if (checkPassword.Checked)
                txtPassword.PasswordChar = '\0';
            else
                txtPassword.PasswordChar = '●';
        }

The complete code should look like this. Now it’s time to run the our program. Everything should work fine now. Here is the complete code.

using System.Windows.Forms;

namespace Password
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            InitializeControls();
        }

        private void InitializeControls()
        {
            checkPassword.Checked = false;
            txtPassword.PasswordChar = '●';
        }

        private void checkPassword_CheckedChanged(object sender, EventArgs e)
        {
            txtPassword.PasswordChar = checkPassword.Checked ? '\0' : '●';
        }
    }
}
Hope this was helpful.

No comments: