当 e.Cancel = true 表示日期时间时,无法关闭表单
本文关键字:表单 时间 Cancel true 日期 表示 | 更新日期: 2023-09-27 17:55:55
在输入无效日期(必须是当前日期或过去日期)后,我有 e.Cancel = true,但随后退出按钮的关闭事件不会触发。 我取出了e.Canel = true语句,一切似乎都很好,但我担心这将在未来引起另一个问题。 对此进行编码的正确方法是什么?
private void maskedTextBoxDate_TypeValidationCompleted(object sender, TypeValidationEventArgs e)
{
if (!e.IsValidInput)
{
toolTip1.ToolTipTitle = "Invalid Date";
toolTip1.Show("The data you supplied must be a valid date in the format mm/dd/yyyy.", maskedTextBoxDate, 40, 25, 2000);
}
else
{
//Now that the type has passed basic type validation, enforce more specific type rules.
DateTime userDate = (DateTime)e.ReturnValue;
if (userDate > DateTime.Today)
{
toolTip1.ToolTipTitle = "Invalid Date";
toolTip1.Show("The date can't be greater than today's date.", maskedTextBoxDate, 40, 25, 2000);
//Cancel property: true if the event should be canceled; otherwise false
e.Cancel = true;
}
}
}
退出按钮关闭事件:
private void cmdExit_Click(object sender, EventArgs e)
{
this.Close();
}
如果以这种方式取消类型验证事件,则 MaskedTextBox 永远不会失去焦点。这个想法是,您不能将数据提交到无效的文本框,因此它"强制"用户在继续之前输入有效数据。您必须决定如何处理文本框中未经验证的数据。
解决此问题的一种方法是将 MaskedTextBox 上的 CausesValidation 属性设置为 false。这可以防止在控件失去焦点时触发验证序列。如果这样做,则需要以其他方式触发验证,例如按钮(例如"保存")。这可能不可行,具体取决于您正在寻找的用户体验。
不是在 Date 控件的 OnExit 中选中日期,而是在窗体的 Close 事件中选中日期,并将 e.cancel 设置为 true 或 false。无论如何,当用户无法摆脱控件时,这很烦人,通常是因为他不知道格式,他只想逃避:-)
斯蒂芬·哈利米
有一个名为 CausesValidation
的Control
属性。 这指示哪些控件在给定焦点时将导致先前聚焦的控件进行验证。
设置maskedTextBoxDate.CausesValidation = true
对于每个父控件,即窗体及其与maskedTextBoxDate
之间的每个容器,设置CausesValidation = false
这将允许您关闭或操作窗体,而不会导致控件进行验证。