在没有用户输入的情况下实现例外 [英] Implementing an exception for no user input

查看:136
本文介绍了在没有用户输入的情况下实现例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是if语句,输入框为有效凭据,我试图获取一个异常方法,如果在文本框的输入中未检测到输入,则将输出一个消息框

Below is the if statement the input boxes to the isvalid credentials, im trying to get create an exception method that will output a message box if no input is detected in the textbox's

使用下面的代码,如果不输入任何内容,它将输出消息"not authenticated"以及IsNullOrWhiteSpace的两个消息.我正在尝试获取它,以便在未输入任何内容的情况下出现一个消息框,要求输入用户名和密码,但是如果这样有意义,我也不想显示未通过身份验证"消息吗?

with the code below, when nothing is entered, it will output the message "not authenticated" as well both the messages for the IsNullOrWhiteSpace. I'm trying to get it so that if nothing is entered, a messagebox will appear asking for a username and password, but I don't want the message "not Authenticated" as well if that makes sense?

如何在下面的代码中实现呢?

How could I implement this into my code below?

public void button1_Click(object sender, EventArgs e)
{
    var username = textBox2.Text;
    var password = textBox1.Text;

    bool isvalid = auth.ValidateCredentials(username, password);
    {
        if (isvalid == true)
        {
            MessageBox.Show("Authenticated!");
        }
        else
        {
            MessageBox.Show("Not Authenticated!");
        }

        if (isvalid = string.IsNullOrWhiteSpace(username))
        {
            MessageBox.Show("Username is empty, please enter a username!");
        }
        if (isvalid = string.IsNullOrWhiteSpace(password))
        {
            MessageBox.Show("Password is empty, please enter a password!");
        }
    }
}

推荐答案

在尝试验证之前进行这些检查,如果其中任何一个为空,则退出该方法:

Do those checks before trying to validate, and exit the method if either are blank:

if (string.IsNullOrWhiteSpace(username))
{
    MessageBox.Show("Username is empty, please enter a username!");
    return;
}
if (string.IsNullOrWhiteSpace(password))
{
    MessageBox.Show("Password is empty, please enter a password!");
    return;
}

bool isvalid = auth.ValidateCredentials(username, password);
if (isvalid)
{
    MessageBox.Show("Authenticated!");
}
else
{
    MessageBox.Show("Not Authenticated!");
}

请注意,由于不必要,我在if语句中删除了对isValid的分配.在bool isValid分配后,我还删除了{ }. { }用于定义新的作用域,通常在if或循环语句之后.他们在这里不痛,但也不是必需的.

Note that I removed the assignment to isValid in your if statements since it's unnecessary. I also removed the { } after the bool isValid assignment. { } is used to define a new scope, typically after an if or loop statement. They din;t hurt anything here but are also not necessary.

这篇关于在没有用户输入的情况下实现例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆