简体   繁体   English

屏蔽的文本框导致VB.NET错误

[英]Masked textbox causing error in VB.NET

When using maskedtextbox in my code, it returns an exception: 在我的代码中使用maskedtextbox时,它返回一个异常:

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: 但是,如果使用文本框代替maskedtextbox,我的代码可以正常工作:

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)

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

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

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