C#在中间层类中抛出异常时,如何获得控制焦点



我正在开发一个Windows Forms应用程序,该应用具有许多文本和组合框,必须手动输入。因此,如果特定的控件为空,则有很多检查。我想阅读UI中的所有验证,并将其移至中间层。这很棒,因为UI现在是无验证的,并且按预期触发了例外,但是现在我不知道哪种控制原因是触发的异常。好吧,我可以,但并非没有干预我的UI,这显然不想要,因为这会使中间层验证不必要,因为我可以在UI中完全做到这一点。因此,简而言之,我想实现的目标是:如果触发验证,我想将重点放在导致异常的控制上,而无需在UI中进行硬设置。这可能吗?或者,如果不是,最好的解决方案是什么?任何帮助。

我创建了一个简单的示例:

私人void btnconfirm_click(对象发送者,EventArgs e){    尝试    {            customer.customertn = txtcustomertn.text;            customer.customername = txtcustomername.text;            customer.customerphone = txtcustomerphone.text; 
  
        MessageBox.Show("Customer TN: " + Customer.CustomerTN + 
                        Environment.NewLine +
                        "Customer Name: " + Customer.CustomerName + 
                        Environment.NewLine +
                        "Customer Phone: " + Customer.CustomerPhone);
   }
   catch (Exception ex)
   {
       MessageBox.Show(ex.Message);
       return;
   }

} //中层类 公共班级客户 { 私有静态字符串customertn; 私有静态字符串自定义; 私人静态字符串Customerphone;

public static string CustomerTN { get { return customerTN; } set { if (value.Length == 0) { throw new Exception("Enter Customer TN..."); } else { customerTN = value; } } } public static string CustomerName { get { return customerName; } set { if (value.Length == 0) { throw new Exception("Enter Customer Name..."); } else { customerName = value; } } } public static string CustomerPhone { get { return customerPhone; } set { if (value.Length == 0) { throw new Exception("Enter Customer Phone..."); } else { customerPhone = value; } } } }

您可以创建Validation类的层次结构。每个Validation类都有一个list可以验证的控件。当进行验证时,如果控件不符合规则,则可以通过显示消息并将重点放在该控件中,例如:

来中止验证。
public abstract class ControlValidator<T> where T : Control
{
     protected List<T> ControlsToValidate;
     public ControlValidator(IEnumerable<T> controls)
     {
          this.ControlsToValidate = new List<T>(controls);
     }
     public abstract bool ValidateControls();
}

然后,如果您想要文本框的验证器,则可以创建一个验证器:

public class TextBoxValidator : ControlValidator<TextBox>
{
     public TextBoxValidator(IEnumerable<TextBox> controls) : base(controls)
     {}
     public override bool ValidateControls()
     {
          foreach(TextBox tb in ControlsToValidate)
          {
              if (tb.Text == "") // This validates the text cannot be empty
              {
                  MessageBox.Show("Text cannot be empty");
                  tb.Focus();
                  return false;
              }
          }
          return True;
     }
}

然后,您将创建一个验证器列表来存储应用程序的所有验证器:

 List<ControlValidator> validators = ...

要验证您的所有控件,您将做一个foreach,例如:

 foreach(var validator in validators)
 {
     if (!validator.ValidateControls())
         break;
 }

一旦发现至少一个控件没有成功验证,

foreach就会中断。希望它有帮助。

最新更新