c# - Masked TextBox 验证文本错误

标签 c# winforms

我在从 WinForms 应用程序的屏蔽文本框中提取日期变量时遇到了一些问题。 尝试读取用户输入日期的代码如下:

DateTime datExpDate = new DateTime();
datExpDate = (DateTime)txtExpDate.ValidateText();     

但我收到 NullReferenceException 错误,即使被屏蔽的文本框肯定不是 Null。

屏蔽文本框的属性包括:

掩码:00/00/0000 验证类型:日期时间 TextMaskFormat: IncludeLiterals

这与我在以前的应用程序中使用的蒙版文本框完全一样,而且它当时有效,为什么现在不呢?

谁能发现我做错了什么?

最佳答案

这是来自 MSDN 的解决方案:

    private void Form1_Load(object sender, EventArgs e)
{
    maskedTextBox1.Mask = "00/00/0000";
    maskedTextBox1.ValidatingType = typeof(System.DateTime);
    maskedTextBox1.TypeValidationCompleted += new TypeValidationEventHandler(maskedTextBox1_TypeValidationCompleted);
    maskedTextBox1.KeyDown += new KeyEventHandler(maskedTextBox1_KeyDown);

    toolTip1.IsBalloon = true;
}

void maskedTextBox1_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.", maskedTextBox1, 0, -20, 5000);
    }
    else
    {
        //Now that the type has passed basic type validation, enforce more specific type rules.
        DateTime userDate = (DateTime)e.ReturnValue;
        if (userDate < DateTime.Now)
        {
            toolTip1.ToolTipTitle = "Invalid Date";
            toolTip1.Show("The date in this field must be greater than today's date.", maskedTextBox1, 0, -20, 5000);
            e.Cancel = true;
        }
    }
}

// Hide the tooltip if the user starts typing again before the five-second display limit on the tooltip expires.

void maskedTextBox1_KeyDown(object sender, KeyEventArgs e)
{
    toolTip1.Hide(maskedTextBox1);
}

链接:http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.validatingtype.aspx

关于c# - Masked TextBox 验证文本错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9208029/

相关文章:

c# - 如何使用 Entity Framework Code First 映射非公共(public) Collection 属性?

c# - 编写自己的音频播放器,从哪里开始

c# - Winforms MessageBox 的形状

c# - 在datagridview c#中使一个单元格可编辑

c# - 如何使用 OpenXml 2.0 将任何文件类型嵌入到 Microsoft Word 中

c# - 如何使用Nest将具有数组值的settings属性添加到ES-index

c# - 如何在线程中传递引用并获取返回值?

检查reg中安装的应用程序路径

c# - 数据库中的重复项

c# - 在等待另一个线程完成它的工作时取消阻塞主线程