【问题标题】:FormClosing Treatment ErrorProviderFormClosing处理ErrorProvider
【发布时间】:2021-05-29 15:35:03
【问题描述】:

我在关闭表单时遇到了问题,我的 ErrorProvider 不允许我这样做。 为了更正它,我做了一个 jerry-rigged 创建一个变量 Boolena 来确认表单是否正在关闭。 我已经尝试过 FormClosing 但 ErrorProvider 仍在验证焦点字段。 有没有人有同样的问题?你是怎么解决的? 我想做得更优雅。

表单初始化

public partial class MyForm: form
{
  private bool _isClosing = false;
...
...
}

使用错误提供程序进行通用验证

private bool ValidatingFields(Control control)
{
  bool eventArgs = false;
  if (!this._isClosing) //Boolean Variable jerry-rigged
  {
    
    if (string.IsNullOrEmpty(control.Text))
    {
      eventArgs = true;
      control.BackColor = Color.Red;
      errorProvider.SetError(control, "Campo Obrigatório!");
    }
    else
    {
      eventArgs = false;
      errorProvider.SetError(control, null);
    }
 }
 return eventArgs;
}

字段验证

private void textName_Validating(object sender, CancelEventArgs e)
{
  e.Cancel = ValidatingFields(textName);
}

事件关闭按钮点击

private void btnCancel_Click(object sender, EventArgs e)
{
  this._isClosing = true;
  this.Close();
}

【问题讨论】:

  • 使用 ErrorProvider 的原因之一是避免 Validating 事件及其e.Cancel 属性。您可以使用其他事件来验证输入,例如 Leave 事件。然后,只有当用户点击确认按钮(OKApply)时,才执行测试以决定是否执行与输入相关的任何动作。因此,用户可以使用窗口的关闭按钮或取消按钮关闭表单,而不会无缘无故地受到骚扰(因为他们只是在任何情况下取消操作),因此不需要处理任何输入。
  • 泰。我会这样做的。

标签: c# .net winforms errorprovider


【解决方案1】:

是的,这种行为没有错。控件验证将触发除 CausesValidation = False 之外的任何按钮单击事件。简而言之,您可以将取消按钮的此属性设置为“False”。这将跳过验证。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    相关资源
    最近更新 更多