Ben Sebuabe

Ben Sebuabe

  • NA
  • 4
  • 5.5k

NullReferenceException was caught

Jun 17 2013 9:12 AM
Please I'm using vb.net 2008 and Sql 2008 and I have to save a picture in to the database. When I run the code initially it was saving and later i realized it was giving me NullReferenceException was caught. Object reference not set to an instance of an object. I' just confused!

The code below


Imports System.Data.SqlClient
Imports System.IO


Private Sub btnImage1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImage1.Click
        'Code to load picture
        Dim OpenFileDialog1 As New OpenFileDialog
        OpenFileDialog1.Filter = "JPG|*.jpg|BITMAP|*.bmp|GIF|*.gif"
        OpenFileDialog1.ShowDialog()
        If OpenFileDialog1.FileName <> "" AndAlso IO.File.Exists(OpenFileDialog1.FileName) Then
            Dim Extention As String = New IO.FileInfo(OpenFileDialog1.FileName).Extension
            Select Case Extention.ToLower
                Case Is = ".jpg", Is = ".bmp", Is = ".gif"
                Case Else
                    MsgBox("Only JPG, BMP and GIF files are allowed. Thank you")
                    Exit Sub
            End Select
            Me.Pic1.Image = Image.FromFile(OpenFileDialog1.FileName)
        End If
    End Sub


'Code to save picture (I stepped into the code and the frmAllottee.Pic1 is there)
Public Sub Save_Picture()
        Dim sql_command As SqlCommand
        Dim mStream As MemoryStream = New MemoryStream()
        'Dim mstream As New MemoryStream()
        frmAllottee.Pic1.BackgroundImage.Save(mstream, frmAllottee.Pic1.BackgroundImage.RawFormat) - This line gives the error
        Dim arrImage() As Byte = mstream.GetBuffer()
        mstream.Close()

        Dim Sql As String = "Insert into Alloc(Pic) VALUES(@Pic)"
        sql_command = New SqlClient.SqlCommand(Sql, Con)
        sql_command.Connection.Open()
        sql_command.Parameters.AddWithValue("@Pic1", arrImage)
        sql_command.ExecuteNonQuery()
        sql_command.Connection.Close()
    End Sub
'


Answers (1)