代码之家  ›  专栏  ›  技术社区  ›  JNYRanger

WinForms TextBox中的MessageBox正在验证事件处理程序

  •  0
  • JNYRanger  · 技术社区  · 11 年前

    我有一个案例,其中一个文本框被验证以确保它不是空白的。但是,在某些边缘情况下,值实际上应该为空。A. Nullable<bool> blankText = null 变量在构造函数中设置。我使用这段代码验证并通过与用户确认,再次检查值是否真的可以为空:

    private void text_Validating(object sender, CancelEventArgs e)
    {
            if (string.IsNullOrWhiteSpace(text.Text))
            {
                do
                {
                    if (blankText.HasValue && !blankText.Value)
                    {
    
                        errorProvider.SetError(text, "Blank or whitespace!");
                        e.Cancel = true;
                        break;
                    }
                    else if (blankText.HasValue && BlankText.Value)
                    {
                        errorProvider.SetError(text, "");
                        e.Cancel = false;
                        break;
                    }
                    else
                    {
                        DialogResult result = MessageBox.Show(this, "Field is blank, or contains only whitespace.\nAre you sure you want to use a blank/whitespace?", String.Empty, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (result == DialogResult.Yes)
                            blankText = true;
                        else
                            blankText = false;
                    }
                }
                while (true);
            }
            else
            {
                e.Cancel = false;
                errorProvider.SetError(text, "");
            }
        }
    

    即使 blankText = null 它仍然会设置errorProvider错误并失败验证。MessageBox对话框从不显示。我知道,根据文档,Microsoft声明如下:

    不要尝试从Enter、GotFocus、Leave、LostFocus、Validating或Validated事件处理程序中设置焦点。这样做会导致应用程序或操作系统停止响应。 Source

    显然,当显示MessageBox时,控件将隐式地失去焦点。。。所以也许这就是为什么会出现这种奇怪的行为。有人能证实这一点吗?有什么更好的处理方法的建议吗?

    1 回复  |  直到 11 年前
        1
  •  0
  •   JNYRanger    11 年前

    为了回应@adriano repetti的评论和一些额外的测试,我从验证事件中删除了提示。我使用的完整解决方案是创建 bool? 如果允许、不允许或未定义空值,则可以检查。如果不允许或未定义,如果值为空,则验证失败。如果由于空白值和新的IsBlankValueAllowed属性而导致验证失败,将显示提示,要求用户确认此行为。我决定使用Property而不是Tag属性中的数据,因为它感觉不那么“被黑”。