我正在尝试从我的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);
}
}
请为我的上述代码提出任何解决方案?
答案 0 :(得分:1)
首先,您需要检查单元格是否包含值。在这种情况下,它的值将是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;
}