尝试捕获验证空文本框

时间:2012-11-22 19:33:38

标签: c# validation try-catch

嘿,所以我有以下代码,如果文本框为空,它应该抛出错误,但它不会继续它会做什么,如果他们没有,并添加一个项目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");
        }

if (txtName.Text == "" || txtAddress.Text == "" || txtArrival.Text == "")
            MessageBox.Show(" Please enter a value into all boxes");
        else
        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

2 个答案:

答案 0 :(得分:4)

try-catch-statement用于捕获和处理异常。如果索引超出范围,如果访问变量的成员设置为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);
}

选择ValidateTextBox方法作为所有文本框的TextChanged事件的错误处理程序。在文本框的Tag属性中插入所需的消息。将BlinkStyle的{​​{1}}属性设置为ErrorProvider。您可以在代码或表单设计器中执行这些设置。

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


<强>更新

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

答案 1 :(得分:2)

你应该尽可能避免尝试捕获,因为性能命中请参见下面的示例:

        //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;

        }