Retreving images from sql to datagrid View windows Forms

Hi i have two colums in table, id and image i have stored my images in the Table ImgTB but the problem is while retreving the images. I just get a red cross.It would be great if some one can help me out
hears my code(a lot confused:))

private void disbtn_Click(object sender, EventArgs e)
        {
            
            SqlDataAdapter adpat = new SqlDataAdapter();
            adpat.SelectCommand = new SqlCommand("select * from ImgTB", con);
            con.Open();
            DataGridViewImageColumn imageColumn = new DataGridViewImageColumn();
            imageColumn.Name = "Picture";
            imageColumn.HeaderText = "picture";
            imageColumn.ImageLayout = DataGridViewImageCellLayout.Zoom;
            try
            {
                imageColumn.Image = byteArrayToImage((byte[])dt.Tables["ImgTB"].Rows[1]["picture"]);
                
            }
            catch(Exception ex)
            {

                MessageBox.Show(e.ToString());
            }
            dataGridView1.Columns.Insert(0, imageColumn);

            adpat.Fill(dt);
            dataGridView1.DataSource = dt;
            con.Close();
       
        }


private Image byteArrayToImage(byte[] byteArrayIn)
        {
            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }

Dani AI

Generated

Good call by @Mitja Bonca on binding instead of assigning a single image to the whole column. The red X you saw usually means the cell value is not an Image (often it is a byte[] or DBNull) or the image decoding failed. Two fixes tend to solve this reliably: bind the byte[] column to a DataGridViewImageColumn, and convert bytes to an Image in CellFormatting while handling nulls.

Example you can drop in after you set dataGridView1.DataSource:

// Create a bound image column (assumes your varbinary(max)/image column is named "Picture").
dataGridView1.AutoGenerateColumns = false;
var picCol = new DataGridViewImageColumn {
    Name = "Picture",
    HeaderText = "Picture",
    DataPropertyName = "Picture",
    ImageLayout = DataGridViewImageCellLayout.Zoom
};
// Show blank (or set a placeholder Image) when DB has NULL.
picCol.DefaultCellStyle.NullValue = null;
dataGridView1.Columns.Add(picCol);

// Convert byte[] -> Image safely and handle empty rows.
dataGridView1.CellFormatting += (s, e) =>
{
    if (dataGridView1.Columns[e.ColumnIndex].Name != "Picture") return;

    if (e.Value == DBNull.Value || e.Value == null) { e.Value = null; e.FormattingApplied = true; return; }

    if (e.Value is byte[] bytes && bytes.Length > 0)
    {
        using (var ms = new MemoryStream(bytes))
        using (var img = Image.FromStream(ms, useEmbeddedColorManagement: false, validateImageData: true))
        {
            e.Value = new Bitmap(img); // clone so we are not tied to the stream
        }
        e.FormattingApplied = true;
    }
};

Notes and gotchas:

  • The clone via new Bitmap(img) avoids the GDI+ requirement that the source stream remain open for the lifetime of the image. Otherwise you can get the red X or GDI+ errors when the stream is disposed. See the .NET docs on the Bitmap-from-stream constructor remark about keeping the stream open. Bitmap(Stream, Boolean).
  • For rows with empty images (re: ), the NullValue setting above displays a blank cell instead of an error glyph; you can also set a placeholder. DataGridViewCellStyle.NullValue.
  • If your table still uses the legacy SQL Server IMAGE type, consider migrating to VARBINARY(MAX); IMAGE is deprecated. ntext, text, and image (Transact-SQL).

Recommended Answers

All 6 Replies

Try to bind data. I mean, fill dataTable and bind it to dgv:

//retreive data from db to datatable:
            SqlDataAdapter adpat = new SqlDataAdapter();
            adpat.SelectCommand = new SqlCommand("select * from ImgTB", con);
            DataTable table = new DataTable("myTable");
            adpat.Fill(table);
            
            //create image column: 
            DataGridViewImageColumn photoColumn = new DataGridViewImageColumn();
            photoColumn.DataPropertyName = "Picture";
            photoColumn.Width = 200;
            photoColumn.HeaderText = "Picture column";
            photoColumn.ReadOnly = true;
            photoColumn.ImageLayout = DataGridViewImageCellLayout.Normal;
            dataGridView1.Columns.Add(photoColumn);           
            //bind data to dgv:
            dataGridView1.DataSource = new BindingSource(table, null);

Try to bind data. I mean, fill dataTable and bind it to dgv:

//retreive data from db to datatable:
            SqlDataAdapter adpat = new SqlDataAdapter();
            adpat.SelectCommand = new SqlCommand("select * from ImgTB", con);
            DataTable table = new DataTable("myTable");
            adpat.Fill(table);
            
            //create image column: 
            DataGridViewImageColumn photoColumn = new DataGridViewImageColumn();
            photoColumn.DataPropertyName = "Picture";
            photoColumn.Width = 200;
            photoColumn.HeaderText = "Picture column";
            photoColumn.ReadOnly = true;
            photoColumn.ImageLayout = DataGridViewImageCellLayout.Normal;
            dataGridView1.Columns.Add(photoColumn);           
            //bind data to dgv:
            dataGridView1.DataSource = new BindingSource(table, null);

hi i get the follwing error i have attacted a picture of the error in the attactment

I cant open the file. Can you create an image? Print screen, cut the image (with photoshoop or something) and paste it here (or on some free server), and paste link here.

I cant open the file. Can you create an image? Print screen, cut the image (with photoshoop or something) and paste it here (or on some free server), and paste link here.

Now its in pdf format

solved IT

, how did you solve it, especially when some datarow has empty images (blob)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.