I wonder if there is better way of validating text box than using KeyDown event. The reason for this is that my event isn’t reacting when it should. For example, in following code check works perfect. I can start typing characters and until 6 or more is entered I am being displayed that I must type at least 6 characters. The problem is that when I type 6 characters and then remove one, making it 5 characters; it doesn’t display the error. Only when I remove more than 2 characters it display my error.
How can I avoid this, or what else I could use to do the check on the fly?
public AuthenticationWindow()
{
InitializeComponent();
// Setting up a password character.
// We are trying to hide what text user is typing.
txtPassword.PasswordChar = char.Parse("-");
txtPassword.MaxLength = 20;
txtUserName.MaxLength = 20;
txtPassword.KeyDown += KeyDownCheck;
}
protected void KeyDownCheck(object sender, KeyEventArgs e)
{
bool validPass = txtPassword.Text.Length < 6;
if (validPass)
lblMessage.Text = "Password can not be shorter than 6 characters!";
else
lblMessage.Text = "Password is valid.";
}
You should use the
TextChangedevent instead.