CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Jul 2021
    Posts
    6

    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
    VictorN's Avatar
    VictorN is online now Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: InvalidCastException

    It is the first item from Google search for "Unable to cast object of type 'System.String' to type 'System.Byte[]":
    https://stackoverflow.com/questions/...pe-system-byte
    Did you try it?
    Victor Nijegorodov

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

Featured