简体   繁体   中英

How to display image stored in a database table in a picturebox when selecting a record in datagridview in c#

This is the problem I'm having. I have a SQL Server table that contains a few columns. One of them is of image datatype. The image is saved as binary data.

On a form I have a dataGridView that shows 3 columns from the table. None of them contains the image. When I click on a record from the dataGridView I want the image displayed in a picturebox from the same form.

This is the code I have so far:

public void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
        SqlConnection cn = new SqlConnection(@" Data Source=HOME-D2CADC8D4F\SQL;Initial Catalog=motociclete;Integrated Security=True");

        if (e.RowIndex >= 0) {
            DataGridViewRow row = dataGridView1.SelectedRows[0];
            textBox1.Text = row.Cells["anf"].Value.ToString();
            textBox2.Text = row.Cells["putere"].Value.ToString();
            textBox3.Text = row.Cells["caprez"].Value.ToString();
            textBox4.Text = row.Cells["greutate"].Value.ToString();
            textBox5.Text = row.Cells["stoc"].Value.ToString();
            textBox6.Text = row.Cells["pret"].Value.ToString();
            textBox7.Text = row.Cells["garantie"].Value.ToString();

            SqlCommand cmd = new SqlCommand("select poza from motociclete where codm '" + dataGridView1.SelectedRows + "'", cn);

            cn.Open();

            try
            {
                SqlDataReader dr = cmd.ExecuteReader();

                if (dr.Read())
                {
                   byte[] picarr = (byte[])dr["poza"];
                    MemoryStream ms = new MemoryStream(picarr);
                    ms.Seek(0, SeekOrigin.Begin);
                    pictureBox1.Image = Image.FromStream(ms);
               }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally {
                cn.Close();
            }
        }
    }

I think it's a syntax error, but I don't know where or how to fix it.

I'd suggest you save the image in some temporary folder and then show it using ImageLocation property.

if (dr.Read())
{
       byte[] picarr = (byte[])dr["poza"];
       string imagePath = "path to temp folder/image123.jpg";
       File.WriteAllBytes(imagePath ,picarr);
       pictureBox1.ImageLocation = imagePath;
}

Main advantage of this approach is that you can easily implement some kind of caching so that you don't have to retrieve images from database every time if they have been selected recently. If your application is busy this can have a strong impact on application performance.

You are missing byte array in your memory stream. So fill your memory stream with byte array by something like this

byte[] picarr = (byte[])dr["poza"];
MemoryStream ms = new MemoryStream(picarr);
pictureBox1.Image = Image.FromStream(ms);

From the following piece of your code:

        SqlDataReader dr;
        try
        {
            dr = cmd.ExecuteReader();
            if (dr.Read())
            {
               byte[] picarr = (byte[])dr["poza"];
                MemoryStream ms = new MemoryStream();
                ms.Seek(0, SeekOrigin.Begin);
                pictureBox1.Image = Image.FromStream(ms);
           }
        }

Take note that your MemoryStream ms =new MemoryStream() provides a MemoryStream with no data. You then use that blank MemoryStream as the source for your image. You should fill the memorystream with the bytes you just read in the previous line.

this is an OLEDB Connection code, but you could get some ideas from it. The images are bitmaps saved as byte[].

int idImagen = Convert.ToInt32(listImagenes.Text.Split(':')[0]);
            ImageConverter ic = new ImageConverter();     
OleDbConnection cnx = new OleDbConnection();
            cnx.ConnectionString = "Your Conection String";
            OleDbCommand cmdx = new OleDbCommand();
            cmdx.Connection = cnx;
            cmdx.CommandText = "SELECT IC.Foto FROM ImageCriminal IC WHERE IC.IdImage=" + idImag;
            cnx.Open();
            byte[] imgRaw = (byte[])cmdx.ExecuteScalar(); //<- Here the byte[] stored in the database gets recovered and stored in imgRaw variable.
            cnx.Close();
            Image imagen = (Image)ic.ConvertFrom((byte[])imgRaw); // This has been working for me from weeks ago!! It's very important to save the files as byte[] inside the DB.
            picBox.Image = imagen;

This code is called from another method. The action is: -Search every picture which PictureId is equal to the i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM