简体   繁体   English

C# - WP8:验证时是否为空?

[英]C# - WP8: error during validating if it is null?

If the Password boxes are empty. 如果密码框为空。 It shows Passwords created Successfully . 它显示Passwords created Successfully I dunno whats wrong I did here. 我不知道我在这里做错了什么。 But, if entered passwords are not matched, if condition works as per code. 但是,如果输入的密码不匹配,则条件按照代码工作。 Error for validating null. 验证null的错误。

Code; 码;

        void savePassword(object sender, RoutedEventArgs e)
        {
            string password1 = createPassword.Password;
            string password2 = repeatPassword.Password;
            if (password1 != null || password2 != null)
            {
                if (password1 == password2)
                {
                    MessageBox.Show("Password Created Successfully");
                }
                else
                {
                    MessageBox.Show("Passwords did not match.");
                }
            }
            else
            {
                MessageBox.Show("Both fields are required");
            }
        }

You can check if the PasswordBox is filled properly with the string.IsNullOrWhiteSpace or string.IsNullOrEmpty methods. 您可以使用string.IsNullOrWhiteSpace或string.IsNullOrEmpty方法检查PasswordBox是否正确填充。 Also, you might want to remove the != because your logic validates as soon as one of the PasswordBoxes has content. 此外,您可能希望删除!=,因为只要其中一个PasswordBox具有内容,您的逻辑就会验证。

Here's a sample: 这是一个示例:

//Is true only if both passwords have content
if(!string.IsNullOrWhiteSpace(password1) && !string.IsNullOrWhiteSpace(password2))

尝试这个

if (password1.Length == 0 || password2.Length == 0)

You have to check that password is empty or null 您必须检查密码是否为空或为空

try this 尝试这个

 if (!string.IsNullOrEmpty(password1) &&!string.IsNullOrEmpty(password2))
            {
                MessageBox.Show("Password Created Successfully");
            }
            else
            {
                MessageBox.Show("Passwords did not match.");
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM