how can i display default image when there is no image in my databse mysql?

poringgunner

Active member
Joined
Feb 23, 2014
Messages
42
Programming Experience
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();


how can i use default image when there is no image in database?
 
Last edited by a moderator:
Get rid of that last `if` block altogether. This bit:
        byte[] image = (byte[])(rd2["IDPic"]);
        if (image == null)
        {
            pictureBox2.Image = null;
        }
        else
        {
            MemoryStream memostream = new MemoryStream(image);
            pictureBox2.Image = System.Drawing.Image.FromStream(memostream);
        }
should be this:
        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);
        }
 
Back
Top Bottom