Dear Sir,

SQL Table employees has data as follows

sno--name----img-----img_path
1-----A----Binary---D:\C2009\BITMAPS\PICT.JPG
2-----B----Binary---D:\C2009\BITMAPS\eric.JPG

Now I want to display picture in picturebox1.
To do this I use this codes, but it does not display picture

on this line: Dim arrPicture() As Byte = CType(dt2.Rows(0)("img_path"), Byte())
it shows this message, please help

Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.

str2 = "select * from employees where sno =" & Val(Me.TextBox1.Text)
        cmd2 = New SqlClient.SqlCommand(str2, con)
        da2 = New SqlClient.SqlDataAdapter(cmd2)
        dt2 = New DataTable
        da2.Fill(dt2)

        If (dt2.Rows.Count >= 1) Then
            Me.TextBox2.Text = dt2.Rows(0)("name")
            Me.TextBox3.Text = dt2.Rows(0)("city")
            Me.TextBox4.Text = dt2.Rows(0)("phone")

            Dim arrPicture() As Byte = CType(dt2.Rows(0)("img_path"), Byte())

            Dim ms As New MemoryStream(arrPicture)

            With PictureBox1
                .Image = Image.FromStream(ms)
                .SizeMode = PictureBoxSizeMode.StretchImage
                .BorderStyle = BorderStyle.Fixed3D
            End With

Hi
Try this

Name (varChar50)
Picture  (Image)
CreateDate(varChar20)--'NOT REALLY NECCESSARY

Now in your Form,
You will need  2 buttons named btnSave and BtnSearch, textbox (txtName)

For the clicked event of btnSearch, add these codes
Dim pictureLocation As String
        Dim a As New OpenFileDialog
        a.Filter = ("Image files| *.JPG")
        pictureLocation = a.FileName
       
            a.ShowDialog()
            Using conn As New System.Data.SqlClient.SqlConnection("Data Source=DENSMAN-PC\SQLEXPRESS;Initial Catalog=aba;Integrated Security=True") 'Insert your connection string here
                conn.Open()

                Using cmd As New SqlClient.SqlCommand("Insert Into ImageData(Name, CreateDate, Picture) Values (@Name, @CreateDate, @Picture)", conn)
                    cmd.Parameters.Add(New SqlClient.SqlParameter("@Name", SqlDbType.VarChar)).Value = txtName.Text
                    cmd.Parameters.Add(New SqlClient.SqlParameter("@CreateDate", SqlDbType.VarChar)).Value = DateTime.Today
                    cmd.Parameters.Add(New SqlClient.SqlParameter("@Picture", SqlDbType.Image)).Value = IO.File.ReadAllBytes(a.FileName)
                    cmd.ExecuteNonQuery()
                End Using


            End Using

Hi
Try this

Name (varChar50)
Picture (Image)
CreateDate(varChar20)--'NOT REALLY NECCESSARY

Now in your Form,
You will need 2 buttons named btnSave and BtnSearch, textbox (txtName)

For the clicked event of btnSearch, add these codes
Dim pictureLocation As String
Dim a As New OpenFileDialog
a.Filter = ("Image files| *.JPG")
pictureLocation = a.FileName

a.ShowDialog()
Using conn As New System.Data.SqlClient.SqlConnection("Data Source=DENSMAN-PC\SQLEXPRESS;Initial Catalog=aba;Integrated Security=True") 'Insert your connection string here
conn.Open()

Using cmd As New SqlClient.SqlCommand("Insert Into ImageData(Name, CreateDate, Picture) Values (@Name, @CreateDate, @Picture)", conn)
cmd.Parameters.Add(New SqlClient.SqlParameter("@Name", SqlDbType.VarChar)).Value = txtName.Text
cmd.Parameters.Add(New SqlClient.SqlParameter("@CreateDate", SqlDbType.VarChar)).Value = DateTime.Today
cmd.Parameters.Add(New SqlClient.SqlParameter("@Picture", SqlDbType.Image)).Value = IO.File.ReadAllBytes(a.FileName)
cmd.ExecuteNonQuery()
End Using


End Using

Dear Sir,

My data is already save and update by following codes
My question was how to display picture in picture box (rertreving from database)

SAVE_IMAGE()
            str = "select * from employees where sno =" & Val(Me.TextBox1.Text)
            dt = GetTable(str)
            If (dt.Rows.Count >= 1) Then
                str = "UPDATE employees SET name = ' " & Trim(TextBox2.Text) & "',"
                str &= "city =  '" & Trim(TextBox3.Text) & "',"
                str &= "phone= '" & Trim(TextBox4.Text) & "',"
                str &= "img_path= '" & Trim(Label5.Text) & "',"
                str &= "img= 'arrImage' "
                str &= " where sno = " & Val(TextBox1.Text)
                ExecuteQuery(str)
                MsgBox("Record updated !! ")
            Else
                str = "insert into EMPLOYEES(SNO,NAME,CITY,PHONE,img_path,img) values ("
                str &= "" & Val(TextBox1.Text) & ",'" & Trim(TextBox2.Text) & "',"
                str &= "'" & Trim(TextBox3.Text) & "','" & Val(TextBox4.Text) & "',"
                str &= "'" & Trim(Label5.Text) & "','"
                str &= " 'arrImage' )"
                ExecuteQuery(str)
                MsgBox("Record inserted !! ")
            End If

Please help again

The problem here is that you don't have a picture in the database for that particular row, you have a null value in the database instead. You need to check for a null value before attempting to load the image:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    'Run it both ways
    Dim o As Object = DBNull.Value
    'Dim o As Object = System.IO.File.ReadAllBytes("C:\picture.bmp")

    If IsDBNull(o) Then
      MessageBox.Show("No picture found")
    End If
  End Sub

The problem here is that you don't have a picture in the database for that particular row, you have a null value in the database instead. You need to check for a null value before attempting to load the image:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    'Run it both ways
    Dim o As Object = DBNull.Value
    'Dim o As Object = System.IO.File.ReadAllBytes("C:\picture.bmp")

    If IsDBNull(o) Then
      MessageBox.Show("No picture found")
    End If
  End Sub

Sir, I have a picture path

sql table fields are as

Sno field type = int
name field type =varchar(50)
img field type =img
img_path field type =varchar(MAX)

and data in table looks like this

sno--name----img-----img_path
1-----A----Binary---D:\C2009\BITMAPS\PICT.JPG
2-----B----Binary---D:\C2009\BITMAPS\eric.JPG

then

How to show picture saved in first row

Please help again

2 things:

1) You have a DBNull.Value in there somewhere

2) I missed this the first time:

on this line: Dim arrPicture() As Byte = CType(dt2.Rows(0)("img_path"), Byte())
it shows this message, please help

Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.

You are converting the string filename (C:\whatever) to a byte[] array. You probably meant to convert the img and not the img_path column.

Humor me and run this code then ZIP and upload the XML file written to your drive. Click on "Go Advanced" next to the quick reply button then "Manage Attachments":

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
    'Change this to your connection string
    Const connStr As String = "Data Source=apex2006sql;Initial Catalog=Leather;Integrated Security=True;"
    Const query As String = "select * from employees"
    Const fileName As String = "C:\tabledata.xml"
    Using conn As New SqlConnection(connStr)
      conn.Open()
      Using cmd As New SqlCommand(query, conn)
        Using dr As SqlDataReader = cmd.ExecuteReader()
          Using dt As DataTable = New DataTable()
            dt.Load(dr)
            dt.TableName = "Table"
            dt.WriteXml(fileName, XmlWriteMode.WriteSchema)
          End Using
        End Using
      End Using
    End Using
  End Sub

2 things:

1) You have a DBNull.Value in there somewhere

2) I missed this the first time:


You are converting the string filename (C:\whatever) to a byte[] array. You probably meant to convert the img and not the img_path column.

Humor me and run this code then ZIP and upload the XML file written to your drive. Click on "Go Advanced" next to the quick reply button then "Manage Attachments":

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
    'Change this to your connection string
    Const connStr As String = "Data Source=apex2006sql;Initial Catalog=Leather;Integrated Security=True;"
    Const query As String = "select * from employees"
    Const fileName As String = "C:\tabledata.xml"
    Using conn As New SqlConnection(connStr)
      conn.Open()
      Using cmd As New SqlCommand(query, conn)
        Using dr As SqlDataReader = cmd.ExecuteReader()
          Using dt As DataTable = New DataTable()
            dt.Load(dr)
            dt.TableName = "Table"
            dt.WriteXml(fileName, XmlWriteMode.WriteSchema)
          End Using
        End Using
      End Using
    End Using
  End Sub

Sir,
I did not understand your folloiwng writing, what does it mean

Humor me and run this code then ZIP and upload the XML file written to your drive. Click on "Go Advanced" next to the quick reply button then "Manage Attachments":

Second:

You have send me codes other than vb.net
Please help me at this ending point

>>Humor me and run this code then ZIP and upload the XML file written to your drive. Click on "Go Advanced" next to the quick reply button then "Manage Attachments":

I meant put that code in your application and run it. It will dump out your entire SQL table to an XML file that you can upload so it can be inspected. You have a null value in there somewhere and that would show where it was

>>You have send me codes other than vb.net

No ... that code is VB.NET.

>>Humor me and run this code then ZIP and upload the XML file written to your drive. Click on "Go Advanced" next to the quick reply button then "Manage Attachments":

I meant put that code in your application and run it. It will dump out your entire SQL table to an XML file that you can upload so it can be inspected. You have a null value in there somewhere and that would show where it was

>>You have send me codes other than vb.net

No ... that code is VB.NET.

Dear Sir

Please xml file

Thanks

As I suggested .. you have NULLs in your table data. Looking at your XML dump this is a complete row with all values:

<Table>
    <sno>1</sno>
    <name> Tariq</name>
    <city>Bahawalpur</city>
    <phone>03006857062</phone>
    <img>YXJySW1hZ2U=</img>
    <img_path>D:\C2009\BITMAPS\PICT.JPG</img_path>
  </Table>

Now take a look at record #3:

<Table>
    <sno>3</sno>
    <name>Tahir</name>
    <city>Multan</city>
    <phone>06125458778</phone>
    <img_path>D:\C2009\BITMAPS\PICT.JPG</img_path>
  </Table>

Notice how that record is missing the <img> tag? That means you don't have an image, so the value is DBNull.Value as I suggested earlier. You have nulls in your data that you need to account for.

As I suggested .. you have NULLs in your table data. Looking at your XML dump this is a complete row with all values:

<Table>
    <sno>1</sno>
    <name> Tariq</name>
    <city>Bahawalpur</city>
    <phone>03006857062</phone>
    <img>YXJySW1hZ2U=</img>
    <img_path>D:\C2009\BITMAPS\PICT.JPG</img_path>
  </Table>

Now take a look at record #3:

<Table>
    <sno>3</sno>
    <name>Tahir</name>
    <city>Multan</city>
    <phone>06125458778</phone>
    <img_path>D:\C2009\BITMAPS\PICT.JPG</img_path>
  </Table>

Notice how that record is missing the <img> tag? That means you don't have an image, so the value is DBNull.Value as I suggested earlier. You have nulls in your data that you need to account for.

Dear Sir,

I refer followings
<Table>
<sno>1</sno>
<name> Tariq</name>
<city>Bahawalpur</city>
<phone>03006857062</phone>
<img>YXJySW1hZ2U=</img>
<img_path>D:\C2009\BITMAPS\PICT.JPG</img_path>
</Table>

img columns has image data type and data shown is in binary type so it is not null.

May this problem is unsovlvable in vb.net?

No, it is possible. Can you create a database backup of your SQL database and zip your project, and upload them both? If it has sensitive information then feel free to upload it somewhere private and PM me the link (NOTE: This is normally against the forum rules but I usually never ask for complete project data files).

I'm telling you .. you have a NULL value in your database. a Nothing reference in Vb.NET will give you a NullReferenceException "reference not set to an instance of an object". However in your original post you stated:

Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.

A System.DBNull is a reference to a null value pulled from a database. You're either looking at two difference databases (design time vs. runtime) or you have a null where you think you have a value.

If Not (IsDBNull(ds.Tables(*tablename*).Rows(inc).Item("Image"))) Then
            Picturebox1.Image = Image.FromStream(New MemoryStream(CType(ds.Tables(*tablename*).Rows(inc).Item("Image"), Byte())))
        Else
            Picturebox1.Image = Picturebox1.ErrorImage
        End If

you can use the code above to check if the row is null. btw, 'inc' is actually an integer. that is what i do for navigation. goodluck pal

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.