0

I'm trying to convert DataGridView data with an image column which is filtered from my SQL database into a PDF file in C#. I wrote this code using iTextSharp, but I get an error

Unable to cast object of type System.Drawing.bitmap to type system byte[]

Can anyone kindly help me out?

Thanks.

Here is my code:

foreach (DataGridViewCell cell in row.Cells)  
{  
    if(row.Cells[0].Value!= null)  
    {  
        pdfTable.AddCell(row.Cells[0].Value.ToString());  
    }  

    if (row.Cells[1].Value != null)  
    {  
        byte[] img = (byte[])row.Cells[1].Value;  
        pdfTable.AddCell(iTextSharp.text.Image.GetInstance(img));  
   }  
}  
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    What the message implies is that you need to convert the bitmap to bite array before atempting a conversion, besides you are using iTextSharp.text to get the image maybe it isn't right – Carlos487 Feb 26 '20 at 20:42
  • then what should i do for converting my datagridview bitmap image into byte array? any resource pls? – Ada Lovelace Feb 26 '20 at 21:22
  • In which line is the error happening I think is happening here byte[] img = (byte[])row.Cells[1].Value; would you please confirm that? – Carlos487 Feb 26 '20 at 21:53
  • yes, you are right.. actually by default- datagridview contain bitmap image when image data called from database.. then i trying to convert this image column data as a pdf, its unable to cast bitmap to byte.. search over internet, but didnt get exact solution yet :( – Ada Lovelace Feb 27 '20 at 04:57
  • I added an answer to your problem. if it helps dont forget to accept and arrow up the answer. Thanks – Carlos487 Feb 27 '20 at 18:29

1 Answers1

1

The error is produced due to a failed casting. According to this Convert a bitmap into a byte array you might need to add a method to perform the conversion.

private byte[] ImageToByte(Image img)
{
    ImageConverter converter = new ImageConverter();
    return (byte[])converter.ConvertTo(img, typeof(byte[]));
}

So you code might look something like this instead.

foreach (DataGridViewCell cell in row.Cells)  
{  
    //... extra code
    if (row.Cells[1].Value != null)  
    {  
        byte[] img = ImageToByte(row.Cells[1].Value);  
        pdfTable.AddCell(iTextSharp.text.Image.GetInstance(img));  
   }  
}  

Hope this helps

Carlos487
  • 1,459
  • 13
  • 17