[英]How to display image stored in a database table in a picturebox when selecting a record in datagridview in c#
[英]C# - How to handle picturebox from datagridview if database record is null
我试图从我的datagridview获取图像并获得成功,但是如果某些记录没有图像或(null),那么我得到了错误(无法将类型为'System.DBNull'的对象转换为类型为'System.Byte []' )。 以下是我的代码:
private void dgridEmployees_SelectionChanged(object sender, EventArgs e)
{
DataGridViewCell cell = null;
foreach (DataGridViewCell selectedCell in dgridEmployees.SelectedCells)
{
cell = selectedCell;
break;
}
if (cell != null)
{
DataGridViewRow row = cell.OwningRow;
lbl_ID.Text = row.Cells[0].Value.ToString();
tboxEmployeeID.Text = row.Cells[1].Value.ToString();
tboxEmployeeName.Text = row.Cells[2].Value.ToString();
dtboxJoiningDate.Text = row.Cells[3].Value.ToString();
tboxDepartment.Text = row.Cells[4].Value.ToString();
tboxPath.Text = row.Cells[5].Value.ToString();
byte[] img = (byte[])dgridEmployees.CurrentRow.Cells[6].Value;
if (img == null)
pictureBox1.Image = null;
else
{
MemoryStream ms = new MemoryStream(img);
pictureBox1.Image = Image.FromStream(ms);
}
}
请为我上面的代码提出任何解决方案?
首先,您需要检查单元格是否不包含任何值。 在这种情况下,它的值将是DBNull.Value
( DBNull
类的单个实例)。 如果比较为假,则只能将其值转换为byte[]
。
if (dgridEmployees.CurrentRow.Cells[6].Value != DBNull.Value)
{
byte[] img = (byte[])dgridEmployees.CurrentRow.Cells[6].Value;
MemoryStream ms = new MemoryStream(img);
pictureBox1.Image = Image.FromStream(ms);
}
else
{
pictureBox1.Image = null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.