C# 尝试捕获验证空文本框

C# 尝试捕获验证空文本框,c#,validation,try-catch,C#,Validation,Try Catch,嘿,我有下面的代码,如果文本框是空的,它应该会抛出错误,但它不是。它只是继续进行,如果它们不是空的,它会做什么,并添加一个带有0或任何东西的项目到列表中,而不是,我的代码有问题吗 private void BtnAdd_Click(object sender, EventArgs e) { try { theVisit.name = txtName.Text; theVisit.address = txtAd

嘿,我有下面的代码,如果文本框是空的,它应该会抛出错误,但它不是。它只是继续进行,如果它们不是空的,它会做什么,并添加一个带有0或任何东西的项目到列表中,而不是,我的代码有问题吗

private void BtnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            theVisit.name = txtName.Text;
            theVisit.address = txtAddress.Text;
            theVisit.arrival = DateTime.Parse(txtArrival.Text);
            //Update theVisit object to reflect any changes made by the user

            this.Hide();
            //Hide the form
        }
        catch (Exception)
        {
            if (txtName.Text == "")
                MessageBox.Show("please enter a customer name");

            if(txtAddress.Text == "") 
                MessageBox.Show("Please enter a customer address");

            if(txtArrival.Text == "")
                MessageBox.Show("Please enter an arrival time");
        }
新的


在可能的情况下,您应该始终避免使用try-catch,因为性能会受到影响,请参见下面的示例:

        //set name
        if(string.IsNullOrEmpty(txtName.Text)) MessageBox.Show("please enter a customer name");
        else theVisit.name = txtName.Text;

        //set address
        if(string.IsNullOrEmpty(txtAddress.Text)) MessageBox.Show("please enter a customer address");
        else theVisit.address = txtAddress.Text;

        //set arrival time
        if(string.IsNullOrEmpty(txtArrival.Text)) MessageBox.Show("please enter an arrival time");
        else {

            DateTime dt = default(DateTime);
            bool successParse = DateTime.TryParse(txtArrival.Text, out dt);

            if(!successParse) MessageBox.Show("please enter a valid arrival time");
            else theVisit.arrival = dt;

        }

try-catch语句用于捕获和处理异常。如果索引超出范围,如果访问设置为null的变量的成员,以及在许多其他情况下,都会引发异常。
TextBox
为空本身不是错误,也不会引发异常

我建议你使用完全不同的方法。在表单中添加一个
ErrorProvider
。您可以在“组件”部分的工具箱中找到它。现在,您可以将以下代码添加到表单中:

private HashSet<Control> errorControls = new HashSet<Control>();

private void ValidateTextBox(object sender, EventArgs e)
{
    var textBox = sender as TextBox;
    if (textBox.Text == "") {
        errorProvider1.SetError(textBox, (string)textBox.Tag);
        errorControls.Add(textBox);
    } else {
        errorProvider1.SetError(textBox, null);
        errorControls.Remove(textBox);
    }
    btnAdd.Enabled = errorControls.Count == 0;
}

private void Form1_Load(object sender, EventArgs e)
{
    txtName.Tag = "Please enter a customer name";
    txtAddress.Tag = "Please enter a customer address";
    errorProvider1.BlinkStyle = ErrorBlinkStyle.NeverBlink;

    ValidateTextBox(txtName, EventArgs.Empty);
    ValidateTextBox(txtAddress, EventArgs.Empty);
}
private HashSet errorControls=new HashSet();
私有void ValidateTextBox(对象发送方,事件参数e)
{
var textBox=发送方作为textBox;
如果(textBox.Text==“”){
errorProvider1.SetError(textBox,(string)textBox.Tag);
errorControls.Add(文本框);
}否则{
errorProvider1.SetError(文本框,null);
errorControls.Remove(文本框);
}
btnAdd.Enabled=errorControls.Count==0;
}
私有void Form1\u加载(对象发送方、事件参数e)
{
txtName.Tag=“请输入客户名称”;
txtAddress.Tag=“请输入客户地址”;
errorProvider1.BlinkStyle=ErrorBlinkStyle.NeverLink;
ValidateTextBox(txtName,EventArgs.Empty);
ValidateTextBox(txtAddress,EventArgs.Empty);
}
选择
ValidateTextBox
方法作为所有文本框的
TextChanged
事件的错误处理程序。在文本框的
标记
属性中插入所需消息。将
ErrorProvider
BlinkStyle
属性设置为
ErrorBlinkStyle.NeverBlink
。您可以在代码或表单设计器中进行这些设置

现在,一个红色错误符号将出现在空文本框旁边。如果将鼠标悬停在它们上面,将出现带有错误消息的工具提示


更新


我更新了上面的代码以自动禁用或启用“添加”按钮。因此,我添加了一个
HashSet
,其中包含当前处于错误状态的所有控件。如果集合为空,则按钮被启用,否则将被禁用。

唯一可能抛出的是DateTime.Parse()<空文本框上的code>.Text不会引发异常,它只返回一个空字符串。使用
string.IsNullOrEmpty(txtName.Text)
检查空值。您的TheVisite对象的设置程序是否引发异常?你能展示你的theVisit对象的类实现吗?theVisit是一个列表,但我想我把它放在了try not catch部分“theVisit是一个列表”中,这是什么意思?List类没有name、address和arrival属性/字段。Nvm我感到困惑,我也是个白痴,因为错误没有显示arrival的原因是因为它有一个默认值,可能我需要一些睡眠或其他东西,如果需要,我可以将类代码添加到上面的帖子中?虽然我现在有两个错误要处理think@TAM没问题。不太清楚为什么我被否决了?嘿,这很好,但是如果文本框是空的,红色符号在那里,我还是按了add,它仍然会将它添加到列表中。在那里可以避免这种情况吗?并且只有在所有文本框中都有itI添加的代码自动启用或禁用按钮时才添加它。请注意,
Add
Remove
方法可以为相同的值调用任意次数,而不会产生错误。
private HashSet<Control> errorControls = new HashSet<Control>();

private void ValidateTextBox(object sender, EventArgs e)
{
    var textBox = sender as TextBox;
    if (textBox.Text == "") {
        errorProvider1.SetError(textBox, (string)textBox.Tag);
        errorControls.Add(textBox);
    } else {
        errorProvider1.SetError(textBox, null);
        errorControls.Remove(textBox);
    }
    btnAdd.Enabled = errorControls.Count == 0;
}

private void Form1_Load(object sender, EventArgs e)
{
    txtName.Tag = "Please enter a customer name";
    txtAddress.Tag = "Please enter a customer address";
    errorProvider1.BlinkStyle = ErrorBlinkStyle.NeverBlink;

    ValidateTextBox(txtName, EventArgs.Empty);
    ValidateTextBox(txtAddress, EventArgs.Empty);
}