Search code examples
c#mysqlvisual-studio-2013picturebox

How to retrieve image from database in c#


an error shows saying that I have invalid parameters for this code... can anyone tell me whats wrong? Im supposed to get the image assigned to the clientID.

private void button1_Click(object sender, EventArgs e)
{
        MySqlConnection conn = new MySqlConnection(mycon);
        MySqlCommand cmd = new MySqlCommand("SELECT clientImage FROM client WHERE clientID='" + label2.Text + "'", conn);

        conn.Open();
        MySqlDataReader myReader = null;
        myReader = cmd.ExecuteReader();

        while (myReader.Read())
        {
            byte[] imgg = (byte[])(myReader["clientImage"]);
            if (imgg == null)
            {
                pictureBox1.Image = null;
            }
            else
            {
                MemoryStream mstream = new MemoryStream(imgg);
                pictureBox1.Image = System.Drawing.Image.FromStream(mstream);
            }
        }
        conn.Close();
}

Solution

  • this code works. MySql Wamp.

    using System.IO;
    
    string appPath = Path.GetDirectoryName(Application.Executable) + @"/student Images/";
    string imagename;
    
    //put this code below to load form.
    getimage();
    if(File.Exist(appPath + imagename)
    {
    PictureBox1.Image = Image.FromFile(appPath + imagename);
    }
    else
    {
    PictureBox1.Image = Properties.Resources.Image_notfound;
    }
    
    private void getimage()
    {
    MySqlConnection connect = new MySqlConnection(con);
    MySqlCommand cmd = new MySqlCommand("SELECT PictureName as 'pic' FROM userprofile where ID='" + datagrid.CurrentRow.Cells["ID"].ToString() + "'");
    cmd.CommandType = CommandType.Text;
    cmd.Connection = connect;
    connect.Open();
    Try
    {
    MySqlDataReader dr = cmd.ExecuteReader();
    while(dr.Read())
    {
    imagename = dr.GetString("pic");
    }
    dr.Close();
    }
    catch(Exception ee)
    {
    Console.WriteLine(ee.ToString());
    }
    finally
    {
    connect.Close();
    }