Results 1 to 7 of 7

Thread: InvalidCastException

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Jul 2021
    Posts
    66

    InvalidCastException

    Hi,

    I am trying to retrieve an image from the SQL database to my form (VB.NET) on a Picturebox.

    See code below:

    Code:
     Private Sub BtnRetrieve_Click(sender As Object, e As EventArgs) Handles BtnRetrieve.Click
            Dim conn As SqlConnection = GetDbConnection()
    
            Dim command As New SqlCommand("SELECT * FROM dbo.tbltenants WHERE nationalID=@nationalid", conn)
            command.Parameters.Add("@nationalid", SqlDbType.VarChar).Value = TxtNationalID.Text
    
            Dim table As New DataTable()
            Dim adapter As New SqlDataAdapter(Command)
            adapter.Fill(table)
    
            TxtNationalID.Text = table.Rows(0)(0).ToString()
            TxtFName.Text = table.Rows(0)(1).ToString()
            TxtLName.Text = table.Rows(0)(2).ToString()
    
            If table.Rows.Count() <= 0 Then
    
                MessageBox.Show("No image available for this National ID")
    
            Else
                Dim img() As Byte
                img = table.Rows(0)(3)
    
                Dim ms As New MemoryStream(img)
                PictureBox1.Image = Image.FromStream(ms)
    
            End If
    
        End Sub
    I receive the error message:

    Code:
    System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'System.Byte[]'.'
    the datatype is Image - at the SQL DB.

    Thanks

  2. #2
    Frenzied Member PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Newport, UK
    Posts
    1,466

    Re: InvalidCastException

    SELECT * is nearly always a bad idea as you will return all columns even if you don't need them, plus they will be returned in the same order as the underlying table - this can cause problems if the table schema changes.

    I am assuming however that table.Rows(0)(3) is actually the correct column, if you you put a breakpoint on that line and see what it looks like in the debugger - is it actually a byte array or is it something else?

  3. #3
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    36,465

    Re: InvalidCastException

    We're also assuming that the error is being thrown on this line:
    Code:
     img = table.Rows(0)(3)
    Is that true? What is table.Rows(0)(3)? If you look at that, it will be an Object, most likely. You must have Option Strict OFF to be expecting the program to implicitly cast that Object as an array of bytes. If the field is correct, as PD is also assuming, and it holds what you think it holds, I'm mildly surprised that the implicit cast didn't work....but only mildly. Implicit casts are bad for a variety of reasons, one of which being that they don't always work. In this case, if the field is right, then the implicit cast isn't working, and that's another good reason not to rely on an implicit cast.

    You might try something as simple as:
    Code:
    img = DirectCast(table.Rows(0)(3),Byte())
    Which is saying, "that object is really an array of bytes. Make it so."
    My usual boring signature: Nothing

  4. #4
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    107,470

    Re: InvalidCastException

    Quote Originally Posted by Shaggy Hiker View Post
    You might try something as simple as:
    Code:
    img = DirectCast(table.Rows(0)(3),Byte())
    Which is saying, "that object is really an array of bytes. Make it so."
    That's not going to work. The fact that the code compiles means that Option Strict is Off, so an explicit cast is not required. That should be remedied, I agree. The error message specifically indicates that the actual data is a String object though, so an explicit cast would still fail just as hard as an implicit one.

  5. #5

    Thread Starter
    Lively Member
    Join Date
    Jul 2021
    Posts
    66

    Re: InvalidCastException

    Yes the below code change failed, giving me the same error message.

    Code:
    img = DirectCast(table.Rows(0)(3),Byte())
    The copyID is an 'image' datatype on the database level...
    Last edited by dr225; Jul 21st, 2021 at 11:45 AM.

  6. #6
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    36,465

    Re: InvalidCastException

    I wasn't paying attention to how implicit casts work. I've avoided them for about 15 years...though I used them at some point prior to that. I thought it might give up and turn it into a string.

    Anyways, we're back to making sure that the type is what you think it is, because it is looking like it is not what you think it is. The first thing you should try is to put a breakpoint on the line that gives you the exception. When execution stops there, highlight this part:

    table.Rows(0)(3)

    and press Shift+F9 to take a look at what that holds. There are other ways to do this, as there always is with VS, but I like this approach. It allows you to look at your leisure. So, it's a string, but if you look at it this way, you may see that it is something that you recognize and realize you had the wrong column. Or it might be something else, but that's a starting point.
    My usual boring signature: Nothing

  7. #7
    Addicted Member
    Join Date
    Jul 2017
    Location
    Exeter, UK
    Posts
    150

    Re: InvalidCastException

    As pointed out by JM the error message reports 'Unable to cast object of type 'System.String', so either you are looking at the wrong column in your data OR you have NOT written the correct data to that column when you populated to data row. Show us how you wrote the record.

    Looking at your previous thread the image column is NOT (3)
    Last edited by bmwpete; Jul 21st, 2021 at 11:44 AM. Reason: grammer

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