ajeesh_ed ajeesh_ed - 3 months ago 13
Vb.net Question

Masked textbox causing error in VB.NET

When using maskedtextbox in my code, it returns an exception:


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


My code is:

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)


But my code works fine if a textbox is used in place of a maskedtextbox like:

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)

Answer

It is better to use one of the parsing methods to validate the date information:

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