2012-02-09 63 views
2

我在WinForms應用程序的屏蔽文本框中提取日期變量時遇到了一些麻煩。 它試圖讀取用戶輸入的日期代碼如下:屏蔽的文本框驗證文本錯誤

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

,但我得到一個NullReferenceException錯誤,甚至當掩模文本框deinately不爲空。

上掩碼文本框中的屬性包括:

面膜:00/00/0000 驗證類型:日期時間 TextMaskFormat:IncludeLiterals

這正是因爲我用以前的應用程序和蒙面的文本框它的工作,那麼爲什麼不現在呢?

任何人都可以發現我做錯了嗎?

+0

ValidateText()轉換到..由'ValidatingType'指定的,你有嗎? – V4Vendetta 2012-02-09 09:24:20

回答

1

下面是從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); 
} 

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