我有一个案例,其中一个文本框被验证以确保它不是空白的。但是,在某些边缘情况下,值实际上应该为空。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时,控件将隐式地失去焦点。。。所以也许这就是为什么会出现这种奇怪的行为。有人能证实这一点吗?有什么更好的处理方法的建议吗?