NullReferenceException被捕获

时间:2013-06-17 13:30:11

标签: vb.net

请使用vb.net 2008和Sql 2008,我必须将图片保存到数据库中。当我最初运行代码时它正在保存,后来我意识到它正在给我NullReferenceException被捕获。你调用的对象是空的。我很困惑!

以下代码

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

2 个答案:

答案 0 :(得分:1)

如果frmAllottee.Pic1.BackgroundImage为空,则会发生这种情况。

ImageBackgroundImage不一样。

答案 1 :(得分:0)

Me.Pic1.Image = Image.FromFile(OpenFileDialog1.FileName)

这行代码与此代码不对应:

frmAllottee.Pic1.BackgroundImage.Save(mstream, frmAllottee.Pic1.BackgroundImage.RawFormat) 

您在保存图片时在图片的Pic1中插入了图片,而您选择了BackgroundImage而不是图像

另外

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()
插入到数据库的@Pic应与添加值时的@ Pic1相同,即(两者都应该是@Pic或您喜欢的任何一个) 香港专业教育学院尝试过,它的工作原理