[英]How can I check if I have an image from my SQL Server database or not using C#
I have a Winforms application which stores products from clients.我有一个 Winforms 应用程序,它存储来自客户的产品。 Those products can have an image to describe them.这些产品可以有一个图像来描述它们。
My problem is that when I want to change my product information I'm getting the following exception:我的问题是,当我想更改我的产品信息时,出现以下异常:
System.InvalidCastException: 'Impossible to cast an object of type "System.DBNull" in type "System.Byte[]" System.InvalidCastException:'不可能在“System.Byte []”类型中转换“System.DBNull”类型的 object
I know this exception occurs because I don't have an image in my database, but I want to know how to check if the image exists.我知道发生此异常是因为我的数据库中没有图像,但我想知道如何检查图像是否存在。
My code:我的代码:
private void chargeImage()
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["db"].ConnectionString);
SqlCommand com1 = new SqlCommand("SELECT * FROM [dbo].[Product] WHERE RFID = '" + dataview.SelectedRows[0].Cells[0].Value.ToString() + "'", con); // Charge image
con.Open();
SqlDataReader dr = com1.ExecuteReader();
if (dr.Read())
{
byte[] picArr = (byte[])dr["image"];
ms = new MemoryStream(picArr);
ms.Seek(0, SeekOrigin.Begin);
pictureBox1.Image = Image.FromStream(ms);
}
con.Close();
}
You can check is it is not DBNull.您可以检查它是否不是 DBNull。 Before前
byte[] picArr = (byte[])dr["image"];
you can check你可以检查
if (!Convert.IsDBNull(dr["image"]))
you can check if they contain null value:您可以检查它们是否包含 null 值:
byte[] picArr = dr.IsDBNull("image")? null: (byte[])dr["image"];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.