Windows Form如何将null返回到picturebox

时间:2021-06-22 15:52:11

UserControl1

的UserControl1

public void showpictures()
{
    {
        SqlConnection conn = new SqlConnection("Data Source=BRAIANX-PC;Initial Catalog=teste;Integrated Security=True");

            SqlCommand comand = new SqlCommand("select photto2 from dbo.tblProduct",conn);
            conn.Open();                    
            SqlDataReader reader = comand.ExecuteReader();

            Image imagem = null;
            if (reader.Read())
            {
                byte[] foto = (byte[])reader["photto2"];

                MemoryStream ms = new MemoryStream(foto);
                imagem = Image.FromStream(ms);
            }
            pictureBox1.Image = imagem;               
    }
}

Form

形成

SqlCommand cm = new SqlCommand("SELECT  tblCategory.Categoryname, tblProduct.Productname,tblProduct.Sinopse,tblProduct.Photto2 FROM tblCategory INNER JOIN tblProduct ON tblCategory.Categoryid = tblProduct.Categoryid where tblCategory.Categoryname= '" + btn.Text + "'", cn);

try
{
    SqlDataReader dr = cm.ExecuteReader();

    flowLayoutPanel2.Controls.Clear();
    flowLayoutPanel2.Update();
    while (dr.Read())     
    {
        UserControl1 user = new UserControl1();
       // user.Nnovo  = (string)dr["Productname"].ToString();//Adds the values ​​of the database in label1 the UserControl
       // user.LastName = (string)dr["Sinopse"].ToString(); //Adds the values ​​of the database in label2 the UserControl

       user.Nnovo = (string)dr[0].ToString();
       user.LastName = (string)dr[1].ToString();
       user.showpictures();

        flowLayoutPanel2.Controls.Add(user);

How I can retrieve image null of PictureBox?

如何检索PictureBox的图像null?

Because have this problem:

因为有这个问题:

It is not possible to convert an object of type 'System.DBNull' to type 'System.Byte[]'

无法将“System.DBNull”类型的对象转换为“System.Byte []”类型

Is there another way to improve this code? I do not know much about byte arrays?

还有其他方法可以改进这段代码吗?我不太了解字节数组?

1 个解决方案

#1


1  

You should check whether the value returned is DbNull.Value:

您应该检查返回的值是否为DbNull.Value:

byte[] foto;

if (reader["photto2"] != DbNull.Value)
{
    foto = (byte[])reader["photto2"];
}
else
{
    foto = null;
}

Or shorter, with the ternary operator:

或者更短,使用三元运算符:

byte[] foto = reader["photto2"] != DbNull.Value ? (byte[])reader["photto2"] : null;

Or, even nicer, with a soft cast:

或者,甚至更好,软铸造:

byte[] foto = reader["photto2"] as byte[];

#1


1  

You should check whether the value returned is DbNull.Value:

您应该检查返回的值是否为DbNull.Value:

byte[] foto;

if (reader["photto2"] != DbNull.Value)
{
    foto = (byte[])reader["photto2"];
}
else
{
    foto = null;
}

Or shorter, with the ternary operator:

或者更短,使用三元运算符:

byte[] foto = reader["photto2"] != DbNull.Value ? (byte[])reader["photto2"] : null;

Or, even nicer, with a soft cast:

或者,甚至更好,软铸造:

byte[] foto = reader["photto2"] as byte[];