从字符串“M”到“Integer”类型的转换无效

时间:2016-04-11 21:21:10

标签: vb.net

我正在尝试通过我想要从ERP系统格式化的字段引用的值转换问题。我无法转换所有值,因为它们被作为字符串拉出,无论变量是设置为整数还是字符串。如果变量以不同的方式定义,那么我在做什么会导致这个错误?

Public Class Class1
Inherits erp.Rule
Public Overrides Function Execute() As erp.RuleResult 
Dim Result As New RuleResult
    Try
        Dim date_recieved As Date
        Dim month As String
        Dim period As String
        Dim Year1 As String
        Dim Year As String 
date_recieved = Data.Fields.GetFieldByAlias("date_received").FieldValue
        month = Format(date_recieved, "M").ToString
        Year = Data.Fields.GetFieldByAlias("yearAR").FieldValue
        period = Data.Fields.GetFieldByAlias("periodAR").FieldValue

        If period = month Then
            If Year = Year1 Then
                Exit Function
            Else
                MessageBox.Show("Date received does not match year", "Invalid Input")
            End If

        Else
            MessageBox.Show("Date received does not match period", "Invalid Input")
        End If

    Catch ex As Exception
        Result.Message = ex.Message
    End Try
    Result.Success = True
    Return Result
  End Function

1 个答案:

答案 0 :(得分:0)

Format不接受字符串参数,通过传递“M”它试图将您提供的数据类型转换为函数接受的数据类型,并且因为字符串不会隐式转换为整数,所以发生错误

要将Date类型格式化为各种格式的字符串,您只需使用日期变量及其后续的.ToString()方法,并将格式规则作为.ToString()的参数

以下是msdn的链接,解释了所有可能的格式选项:https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1