【发布时间】:2019-10-17 17:37:06
【问题描述】:
我有一个名为 tblStaff 的表,其中名为 staffImage 的列具有允许存储 Null 的 Image 数据类型。如果用户提供他的照片,那么此列会将图像存储为二进制数据,如果他不提供他的图像,那么它将存储 Null 值。如果此列为 null 值,则 Resource 文件夹中的图像应显示在 pictureBox1 中,如果此列具有二进制数据,则此列中存储为二进制数据的图像应显示在 pictureBox1 中。
CREATE TABLE tblStaff
(
staffId int not null identity Primary Key,
staffName varchar(50) not null,
staffUserName varchar(25) not null,
staffPassword varchar(30) not null,
staffPhone varchar(15) not null,
staffRole int not null,
staffStatus tinyint not null,
**staffImage image**
)
ALTER PROC [dbo].[sp_GetStaffImage]
@staffId varchar(150)
as
SELECT Stf.staffImage as 'Image' FROM tblStaff Stf WHERE
staffID=@staffId
.
.
.
.
string staffID = Convert.ToString(dataGridViewStaff.Rows[e.RowIndex].Cells["Staff Id"].Value);
..............
.............
..........
...........
SqlConnection con1 = new SqlConnection(cs);
con.Open();
SqlCommand cmd1 = new SqlCommand("sp_GetStaffImage", con);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("@staffId", staffID);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
sda1.Fill(ds);
if(ds.Tables[0].Rows.Count>0)
{
var img = (byte[])ds.Tables[0].Rows[0][0];
if (img != Null) //code if the data in column named staffImage is
Binary data then show the image
in PictureBox1 from the database.
{
MemoryStream ms = new MemoryStream(img);
pictureBox1.Image = new Bitmap(ms);
}
else //code if the data in column named staffImage is Null then show the image in PictureBox1
from Resource folder .
{
pictureBox1.ImageLocation = "Resources/human.png";
}
}
con.Close();
通过运行上面的代码,我得到了如下异常: 无法将“System.DBNull”类型的对象转换为“System.Byte[]”类型。
【问题讨论】:
标签: c# sql .net windows ado.net