来自:http://msdn.microsoft.com/zh-cn/library/kkx4h3az(VS.80).aspx
-
-
初始化 MaskedTextBox 控件
-
当字符不符合掩码时使用 MaskInputRejected 事件处理程序向用户报警
-
为 ValidatingType 属性分配类型,并在用户试图提交的值对类型无效时,使用 TypeValidationCompleted 事件处理程序向用户报警
有关 MaskedTextBox 控件(该控件演示诸如使用自定义数据类型进行验证等高级功能)的完整工作版本,请参见 MaskedTextBox 控件示例。
创建项目和添加控件
向窗体添加 MaskedTextBox 控件
-
打开希望在其中放置 MaskedTextBox 控件的窗体。
-
将 MaskedTextBox 控件从“工具箱”中拖到窗体上。
-
右击控件并选择“属性”。在“属性”窗口中,选择“掩码”属性,并单击属性名称旁边的“...”(省略号)按钮。
-
在“输入掩码”对话框中,选择“短日期”掩码,并单击“确定”。
-
在“属性”窗口中,将 BeepOnError 属性设置为 true。设置此属性后,每次用户试图输入不符合掩码定义的字符时,就会听到短的警告音。
发生输入错误时向用户报警
为被拒绝的掩码输入添加气球状提示
-
返回到“工具箱”,向窗体添加 ToolTip。
-
为在发生输入错误时会引发 ToolTip 的 MaskInputRejected 事件创建事件处理程序。气球状提示将持续五秒保持可见状态,或在用户单击它后消失。
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); }
键入无效类型时向用户报警
为无效的数据类型添加气球状提示
-
在窗体的 Load 事件处理程序中,将表示 DateTime 类型的 Type 对象分配给 MaskedTextBox 控件的 ValidatingType 属性:
private void Form1_Load(Object sender, EventArgs e) { // Other code maskedTextBox1.ValidatingType = typeof(System.DateTime); maskedTextBox1.TypeValidationCompleted += new TypeValidationEventHandler(maskedTextBox1_TypeValidationCompleted); }
-
为 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; } }
-