用到picturebox控件。以下是完整的代码(函数)
txtorderid是一个文本框内容,就是更新数据表的条件ID。
app.sqldb.cn 用cn代替就可以了。
SAVePIc是我定义的函数名称,即:
'从数据库中加载图片到图片框
Private Function ShowPic() As Boolean
Dim dtpic As New DataTable()
Dim dapic As SqlDataAdapter
Try
dtpic.Clear()
Me.PicBox.Image = Nothing
Dim picsql As String = "select orderimage from productorder where productno=@bm"
Dim piccmd As New SqlCommand(picsql, Cn)
With piccmd
.Parameters.Add(New SqlParameter("@bm", SqlDbType.VarChar, 15)).Value() = Trim(txtOrderID.Text)
End With
If State = ConnectionState.Closed = True Then Open()
dapic = New SqlDataAdapter(piccmd)
dapic.Fill(dtpic)
If dtpic.Rows.Count = 0 Then Exit Function
'If dtpic.Rows(0)("orderimage") Is System.DBNull.Value And dtpic.Rows(0)("orderimage") = 0 Then Exit Function
'
If IIf(IsDBNull(dtpic.Rows(0)("orderimage")), "", dtpic.Rows(0)("orderimage")) Is System.DBNull.Value Then Exit Function
If IIf(IsDBNull(dtpic.Rows(0)("orderimage")), "0", dtpic.Rows(0)("orderimage")).length < 10 Then Exit Function
Dim arrPicture() As Byte = CType(dtpic.Rows(0)("orderimage"), Byte())
Dim ms As New MemoryStream(arrPicture)
With PicBox
.Image = Image.FromStream(ms)
End With
ShowPic = True
Catch e As SqlException
MessageBox.Show(e.Message, e.Source)
ShowPic = False
Finally
这是用VB.NET写的,保存图片到数据库的函数。已经用了很久了,没出现问题。
Try
Dim picsql As String = "update products set orderimage=@orderimage where productno=@productno"
Dim piccmd As New SqlCommand(picsql, Cn) 'Cn 数据库连接 SQL2000的数据库
With piccmd
.Parameters.Add(New SqlParameter("@productno", SqlDbType.VarChar, 15)).Value() = Trim(txtOrderID.Text)
If Me.PicBox.Image Is Nothing Then ‘判断图片是否为空
.Parameters.Add(New SqlParameter("@orderimage", SqlDbType.Image)).Value = System.DBNull.Value
Else
Dim ms As New MemoryStream()
PicBox.Image.Save(ms, PicBox.Image.RawFormat.Jpeg)
Dim arrImage() As Byte = ms.GetBuffer
ms.Close()
.Parameters.Add(New SqlParameter("@orderimage", SqlDbType.Image)).Value = arrImage
End If
End With
If App.SQLDB.Cn.State = ConnectionState.Closed = True Then App.SQLDB.Cn.Open()
piccmd.ExecuteNonQuery()
MsgBox("图片操作成功!", MsgBoxStyle.Information)
Catch E As SqlException
MessageBox.Show(E.Message, E.Source, MessageBoxButtons.OK, MessageBoxIcon.Information)
SavePic = False
End Try
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Data.SqlClient;