蒙面文本框导致 VB.NET 中出现错误

Masked textbox causing error in VB.NET

在我的代码中使用 maskedtextbox 时,returns 出现异常:

Conversion from string "" to type 'Date' is not valid

我的代码是:

Dim msg, first, second As String
Dim firstdate, seconddate As Date
first = MaskedTextBox1.Text
second = MaskedTextBox2.Text
firstdate = CDate(first)
seconddate = CDate(second)
msg = "Days from today: " & DateDiff(DateInterval.Month, firstdate, seconddate)
MsgBox(msg)

但是如果使用文本框代替掩码文本框,我的代码可以正常工作,例如:

Dim msg, first, second As String
Dim firstdate, seconddate As Date
first = TextBox3.Text
second = TextBox4.Text
firstdate = CDate(first)
seconddate = CDate(second)
msg = "Days from today: " & DateDiff(DateInterval.Month, firstdate, seconddate)
MsgBox(msg)

最好使用其中一种解析方法来验证日期信息:

If DateTime.TryParse(first, firstdate) AndAlso _
   DateTime.TryParse(second, seconddate) Then
  msg = "Days from today: " & DateDiff(DateInterval.Day, firstdate, seconddate)
  MessageBox.Show(msg)
Else
  MessageBox.Show("Invalid dates entered.")
End If