掩码文本框导致VB.NET错误

时间:2015-03-03 17:46:20

标签: vb.net textbox maskedtextbox

在我的代码中使用maskedtextbox时,它会返回一个异常:

  

从字符串转换""输入'日期'无效

我的代码是:

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)

1 个答案:

答案 0 :(得分:0)

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

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