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?

6
  • You are using tostring, in essential trying to match a string with an integer. Parse Nationality1 to an integer in stead of doing tostring Commented Jul 18, 2017 at 7:13
  • i got another error: Conversion from type 'DBNull' to type 'String' is not valid. Commented Jul 18, 2017 at 7: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)). Commented Jul 18, 2017 at 7:27
  • 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. Commented Jul 18, 2017 at 8: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). Commented Jul 18, 2017 at 8:25

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.