当我的数据库mysql中没有图像时,如何显示默认图像?

poringgunner

活跃成员
已加入
2014年2月23日
留言内容
42
编程经验
Beginner
            string myConnection = ("datasource = 193.167.1.1; port = 3306; username = root; password = 123");
            MySqlConnection myConn = new MySqlConnection(myConnection);
            MySqlCommand mycommand2 = myConn.CreateCommand();
            mycommand2.CommandText = "SELECT * FROM jansen.studentpictures WHERE IDNo = '" + ID_Numtext.Text + "';";
            try
            {
                myConn.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            MySqlDataReader rd2 = mycommand2.ExecuteReader();
            while (rd2.Read())
            {
                    byte[] image = (byte[])(rd2["IDPic"]);
                    if (image == null)
                    {
                        pictureBox2.Image = null;
                    }
                    else
                    {
                        MemoryStream memostream = new MemoryStream(image);
                        pictureBox2.Image = System.Drawing.Image.FromStream(memostream);
                    }
                    ID_Numtext.Clear();
               
            }
                if (pictureBox2.Image == null)                                /*here is my problem.. i dont know what is the best condition here for showing the                                                                                                               default image in picturebox. the default image is idnotavailable.Image*/
                {
                    pictureBox2.Image = idnotavailable.Image;
                    ID_Numtext.Clear();
                }
            myConn.Close();


数据库中没有图像时,如何使用默认图像?
 
由主持人最后编辑:

金西尼

C#论坛主持人
工作人员
已加入
2011年4月23日
留言内容
3,573
地点
悉尼,澳大利亚
编程经验
10+
完全摆脱最后一个if块。这一点:
        byte[] image = (byte[])(rd2["IDPic"]);
        if (image == null)
        {
            pictureBox2.Image = null;
        }
        else
        {
            MemoryStream memostream = new MemoryStream(image);
            pictureBox2.Image = System.Drawing.Image.FromStream(memostream);
        }
应该是这样的:
        if (rd2.IsDBNull(rd2.GetOrdinal("IDPic")))
        {
            pictureBox2.Image = idnotavailable.Image;
        }
        else
        {
            byte[] image = (byte[])(rd2["IDPic"]);
            MemoryStream memostream = new MemoryStream(image);
            pictureBox2.Image = System.Drawing.Image.FromStream(memostream);
        }
 
最佳 底部