1

I am looping thorugh a datatable and and printing each row to the console and I keep on getting a dbnull error. I inserted an if statement in my loop to try and catch it, but I can't seem to get it to work. Any ideas?

Thanks!

                Do While reader.Read
                For i As Integer = 0 To reader.FieldCount - 1

                    If reader.IsDBNull(i) Then
                        Console.Write(Nothing)
                    Else
                        Console.Write(reader.GetString(i))
                    End If

                Next
                Console.WriteLine(Environment.NewLine())
1
  • Check if you are really getting a DBNull error and post it. Commented Jan 1, 2012 at 16:45

3 Answers 3

2

Changing Console.Write(Nothing) to Console.Write("Nothing") might remove one error, and reader.GetString(i) might throw InvalidCastException errors - you should catch this. reader.IsDBNull(i), however, looks correct.

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

1 Comment

Yeah, it didn't like the write(nothing). I ended up just putting " , " as the string and it works fine now.
1

I have never used the reader methods, but Console.Write(Nothing) would likely have issues. Try this:

        Do While reader.Read
        For i As Integer = 0 To reader.FieldCount - 1

            If reader.Item(i) Is DBNull.Value Then
                Console.Write("")
            Else
                Console.Write(CStr(reader.Item(i)))
            End If

        Next
        Console.WriteLine(Environment.NewLine())
    Loop

Comments

1

Why not simply change it to

        If NOT isdbnull(reader.Item(i)) Then
            Console.Write("")
        Else
            Console.Write(CStr(reader.Item(i)))
        End If

That has always worked better for me. I dont know if there is a DBNull vs DBNull.value issue here.

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.