本演练涉及以下任务:
初始化 MaskedTextBox 控件
MaskInputRejected当字符不符合掩码时,使用事件处理程序向用户发出警报
将类型分配给 ValidatingType 属性并使用 TypeValidationCompleted 事件处理程序在尝试提交的值对类型无效时向用户发出警报
创建项目并添加控件
向窗体添加 MaskedTextBox 控件
打开要在其中放置控件的 MaskedTextBox 窗体。
将 MaskedTextBox 控件从 工具箱 拖动到窗体。
右键单击控件并选择 “属性”。 在 “属性” 窗口中,选择 “掩码 ”属性,然后单击属性名称旁边的 ... (省略号)按钮。
在 “输入掩码 ”对话框中,选择 “短日期 ”掩码,然后单击“ 确定”。
在 “属性” 窗口中,将 BeepOnError 属性设置为
true
。 每当用户尝试输入违反掩码定义的字符时,此属性都会发出简短的蜂鸣声。
有关 Mask 属性支持的字符的摘要,请参阅 Mask 属性的“备注”部分。
提醒用户输入错误
为被拒绝的掩码输入添加气球提示
返回到 工具箱 ,并向窗体添加一个 ToolTip 。
为 MaskInputRejected 事件创建一个事件处理程序,以便在发生输入错误时引发 ToolTip。 气球提示在 5 秒内保持可见,或者直到用户单击它。
public void Form1_Load(Object sender, EventArgs e) { ... // Other initialization code maskedTextBox1.Mask = "00/00/0000"; maskedTextBox1.MaskInputRejected += new MaskInputRejectedEventHandler(maskedTextBox1_MaskInputRejected) } void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { toolTip1.ToolTipTitle = "Invalid Input"; toolTip1.Show("We're sorry, but only digits (0-9) are allowed in dates.", maskedTextBox1, maskedTextBox1.Location, 5000); }
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Me.ToolTip1.IsBalloon = True Me.MaskedTextBox1.Mask = "00/00/0000" End Sub Private Sub MaskedTextBox1_MaskInputRejected(sender as Object, e as MaskInputRejectedEventArgs) Handles MaskedTextBox1.MaskInputRejected ToolTip1.ToolTipTitle = "Invalid Input" ToolTip1.Show("We're sorry, but only digits (0-9) are allowed in dates.", MaskedTextBox1, 5000) End Sub
将用户警报到无效的类型
为无效数据类型添加气球提示
在窗体的Load事件处理程序中,将表示TypeDateTime类型的对象分配给MaskedTextBox控件的ValidatingType属性。
private void Form1_Load(Object sender, EventArgs e) { // Other code maskedTextBox1.ValidatingType = typeof(System.DateTime); maskedTextBox1.TypeValidationCompleted += new TypeValidationEventHandler(maskedTextBox1_TypeValidationCompleted); }
Private Sub Form1_Load(sender as Object, e as EventArgs) // Other code MaskedTextBox1.ValidatingType = GetType(System.DateTime) End Sub
为 TypeValidationCompleted 事件添加事件处理程序:
public void maskedTextBox1_TypeValidationCompleted(object sender, TypeValidationEventArgs e) { if (!e.IsValidInput) { toolTip1.ToolTipTitle = "Invalid Date Value"; toolTip1.Show("We're sorry, but the value you entered is not a valid date. Please change the value.", maskedTextBox1, 5000); e.Cancel = true; } }
Public Sub MaskedTextBox1_TypeValidationCompleted(sender as Object, e as TypeValidationEventArgs) If Not e.IsValidInput Then ToolTip1.ToolTipTitle = "Invalid Date Value" ToolTip1.Show("We're sorry, but the value you entered is not a valid date. Please change the value.", maskedTextBox1, 5000) e.Cancel = True End If End Sub