【问题标题】:Conversion from string "" to type 'Integer' is not valid - ASP.net using VB从字符串“”到类型“整数”的转换无效 - 使用 VB 的 ASP.net
【发布时间】:2017-07-18 07:11:06
【问题描述】:

此错误一直显示在这行代码

ApplicantSett.Nationality1 = IIf(IsDBNull(ds.Tables("Applicant").Rows(i)("Nationality1").ToString) Or IsNothing(ds.Tables("Applicant").Rows(i)("Nationality1").ToString),
                               Nothing, CInt(ds.Tables("Applicant").Rows(i)("Nationality1").ToString))

变量 Nationality1 是一个整数,它在数据库中为空,所以它没有转换。我该怎么办?

【问题讨论】:

  • 您正在使用tostring,本质上是尝试将stringinteger 匹配。将 Nationality1 解析为整数而不是 tostring
  • 我遇到了另一个错误:从“DBNull”类型到“String”类型的转换无效。
  • 在同时检查DBNullNothing 条件时删除ToStringIIf(IsDBNull(ds.Tables("Applicant").Rows(i)("Nationality1")) Or IsNothing(ds.Tables("Applicant").Rows(i)("Nationality1")), Nothing, CInt(ds.Tables("Applicant").Rows(i)("Nationality1").ToString))
  • IsDbNullToString 值的测试是错误的:ToString 已将可能的 DbNull 值转换为空字符串,这不再是 DbNull。所以这将始终返回 False。解决方案:删除 .ToString。
  • 您不需要测试 IsNothing,DataRow 字段永远不会是 Nothing,而是 DbNull。另外,当它是 Nothing 时,ToString 会崩溃(NullReferenceException)。

标签: sql asp.net vb.net


【解决方案1】:
Dim nationality As Object = ds.Tables("Applicant").Rows(i)("Nationality1")

If (nationality IsNot Nothing 
AndAlso nationality <> System.DBNull.Value 
AndAlso Not System.String.IsNullOrEmpty(nationality.ToString()) Then
    Dim output As Integer
    If (System.Int32.TryParse(value, output)) Then
        ApplicantSett.Nationality1 = output
    End If
End If

如果您有很多返回值需要解析,那么您可以编写自己的 Parser 来在一行代码中解析该值。

Integer.Parse 与 CInt - https://stackoverflow.com/a/423910/2046832

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多