繁体   English   中英

屏蔽的文本框验证文本错误

[英]Masked TextBox Validating Text Error

我从WinForms应用程序中从蒙版文本框中提取的日期变量遇到了一些麻烦。 尝试读取用户输入日期的代码如下:

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

但是,即使蒙版文本框确实不是Null,我也会收到NullReferenceException错误。

被屏蔽的文本框上的属性包括:

掩码:00/00/0000验证类型:DateTime 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM