【问题标题】:Validating user entry on the fly causing some complications即时验证用户输入会导致一些并发症
【发布时间】:2011-12-05 07:24:04
【问题描述】:

我想知道是否有比使用 KeyDown 事件更好的验证文本框的方法。这样做的原因是我的事件没有在应该的时候做出反应。例如,在以下代码中检查工作完美。我可以开始输入字符,直到输入 6 个或更多字符,系统显示我必须输入至少 6 个字符。问题是当我输入 6 个字符然后删除一个,变成 5 个字符;它不显示错误。只有当我删除超过 2 个字符时,它才会显示我的错误。

我怎样才能避免这种情况,或者我还能用什么来进行即时检查?

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.";
}

【问题讨论】:

标签: c# .net textbox validation


【解决方案1】:

您应该改用TextChanged 事件。

textBox1.TextChanged += new EventHandler(txtPassword_TextChanged);

private void txtPassword_TextChanged(object sender, EventArgs 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.";

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多