Results 1 to 4 of 4

Thread: Conversion from type 'DBNull' to type 'String' is not valid

  1. #1

    Thread Starter
    Lively Member
    Join Date
    May 2009
    Posts
    66

    Conversion from type 'DBNull' to type 'String' is not valid

    I met that error when i use this code :

    Code:
      Dim K As String = sqlcommand.ExecuteScalar()
    If items in column is empty it will show that error,

    How can i overcome it without use trycatch or ...

  2. #2
    Fanatic Member manhit45's Avatar
    Join Date
    May 2009
    Location
    Ha noi - Viet Nam
    Posts
    826

    Re: Conversion from type 'DBNull' to type 'String' is not valid

    Quote Originally Posted by taybacuniversity View Post
    I met that error when i use this code :

    Code:
      Dim K As String = sqlcommand.ExecuteScalar()
    If items in column is empty it will show that error,

    How can i overcome it without use trycatch or ...

    If you want to overcome it you have to call string method to convert to string type.

    Code:
      Dim K As String = sqlcommand.ExecuteScalar.tostring
    --***----------***-----

    If i help you please rate me.

    Working with Excel * Working with String * Working with Database * Working with array *

    K51 ĐH BÁCH KHOA HÀ NỘI - Khoa CNTT pro.

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Conversion from type 'DBNull' to type 'String' is not valid

    It depends exactly what you're trying to achieve, which you have conveniently failed to tell us. The previous suggestion will return an empty string so, if that's what you want in that situation, that's what you should do. Alternatively you can assign the result to an Object variable and then check whether it is DBNull.Value first, before casting as type String.

    If your original code compiled then you must have Option Strict Off, which I suggest you change for this and every other project.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  4. #4

    Thread Starter
    Lively Member
    Join Date
    May 2009
    Posts
    66

    Re: Conversion from type 'DBNull' to type 'String' is not valid

    Thanks for all.

    I used tostring method and it work.

    Did that method convert to string ?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width