请我使用 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