代码之家  ›  专栏  ›  技术社区  ›  KJSR

TryParse日期何时无效自定义错误消息

  •  -1
  • KJSR  · 技术社区  · 6 年前

    TryParse.Date() 验证通过文本框传递的日期,如果无效,则显示自定义消息框警告。

    但是,在测试时,而不是返回 False 在显示消息框时,它只是显示一个错误异常 String passed is not a valid Date

    这是我的密码

    If Not Date.TryParse(txtDate.Text, "dd/MM/yyyy")
        MsgBox("Please enter a valid Date", MsgBoxStyle.Critical)
        Return
    End If
    

    所以如果我传入一个字符串值 01/01/99d 它将显示异常消息,而不是返回并进入循环?

    有什么建议吗?

    2 回复  |  直到 6 年前
        1
  •  2
  •   the_lotus    6 年前

    事实并非如此 TryParse works . 第二个参数需要一个日期对象。我强烈建议你打开这个选项。

    你要找的是 TryParseExact . 它允许您设置自己的格式,但仍然需要将日期对象作为参数传递。页面上的示例很好,但我认为可以将参数设置为Nothing。

    Dim theDate As Date
    
    If Not DateTime.TryParseExact(txtDate.Text, "dd/MM/yyyy", Nothing, Nothing, theDate) Then
    ...
    

    注: 基于Rango注释,即使使用“/”作为分隔符。这可能会导致不同文化的人产生问题。我强烈建议您正确设置文化,而不是什么都不使用。

        2
  •  1
  •   Martin Joseph Silber    6 年前

    如果你看一下 Date.TryParse 您将看到第二个参数应该是 Date 通过引用传递的:

    Date.TryParse Definition

    这意味着第二个参数不应是字符串。

    您可以更改代码以正确使用第二个参数,如下所示:

    Dim dateParam As Date
    
    If Not Date.TryParse(txtDate.Text, dateParam) Then
        MsgBox("Please enter a valid Date", MsgBoxStyle.Critical)
        Return
    End If