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

时间:2013-09-02 05:51:09

标签: c# windows-phone-8

如果密码框为空。它显示Passwords created Successfully。我不知道我在这里做错了什么。但是,如果输入的密码不匹配,则条件按照代码工作。验证null的错误。

代码;

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

3 个答案:

答案 0 :(得分:2)

您可以使用string.IsNullOrWhiteSpace或string.IsNullOrEmpty方法检查PasswordBox是否正确填充。此外,您可能希望删除!=,因为只要其中一个PasswordBox具有内容,您的逻辑就会生效。

以下是一个示例:

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

答案 1 :(得分:0)

试试这个

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

答案 2 :(得分:0)

您必须检查密码为空或为空

试试这个

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