0

this error keeps showing on this line of code

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))

the variable Nationality1 is an Integer and it is null in the database so it is not converting. what should I do?

  • You are using `tostring`, in essential trying to match a `string` with an `integer`. Parse `Nationality1` to an integer in stead of doing `tostring` – Tikkes Jul 18 '17 at 07:13
  • i got another error: Conversion from type 'DBNull' to type 'String' is not valid. – Patricia Matar Jul 18 '17 at 07:23
  • 1
    Remove `ToString` when checking both `DBNull` & `Nothing` conditions: `IIf(IsDBNull(ds.Tables("Applicant").Rows(i)("Nationality1")) Or IsNothing(ds.Tables("Applicant").Rows(i)("Nationality1")), Nothing, CInt(ds.Tables("Applicant").Rows(i)("Nationality1").ToString))`. – Tetsuya Yamamoto Jul 18 '17 at 07:27
  • it's not working!!!! because its value in the db is NULL – Patricia Matar Jul 18 '17 at 07:43
  • 1
    The test of `IsDbNull` on a `ToString` value is wrong: The ToString has converted a possible DbNull value to an empty string, which is not DbNull anymore. So this will always return False. Solution: remove the .ToString. – Hans Kesting Jul 18 '17 at 08:24
  • 1
    You don't need to test for IsNothing, a DataRow field will never be Nothing, but DbNull. Plus when it were Nothing, then the ToString would crash (NullReferenceException). – Hans Kesting Jul 18 '17 at 08:25

1 Answers1

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

If you have a lots of returned values which are needed to be parsed, then you may write your own Parser to parse the value in one line of code.

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

Thiam Hooi
  • 111
  • 2
  • 8