3

I have a seemingly simple problem, I have created a DataTable dynamically and I add rows to it just fine. However I have a column that will have a flag which is an image. I had already imported the two flags(.png images) into the projects resources. However I cant set the DataType for the column as System.Type.Bitmap as DataColumn doesnt support that as can be seen here HERE . I had seen a solution that said I set DataType as below

dataColumn = new DataColumn("Flag");
dataColumn.DataType = System.Type.GetType("System.Byte[]"); //Replacing System.Byte[] with System.Type.Bitmap throws Type Exception
dataTable.Columns.Add(dataColumn);

However that throws an Exception stating that compiler expected Byte[] but got Bitmap.

Here is how I add rows to DataTable

row["Part Number"] = part;
row["Module Name"] = populator.LookUpAValue(moduleSql);
row["Flag"] = Properties.Resources.Yellow_Flag;
row["Location"] = populator.LookUpAValue(nameSql);
dataTable.Rows.Add(row);

Here is my question, which DataType do I save the image column as so when I display to a DataGridView I see the images displayed. Without setting DataType on the DataGridView instead of images being displayed, I get text System.Drawing.Bitmap

CDspace
  • 2,639
  • 18
  • 30
  • 36
Dev
  • 1,146
  • 2
  • 19
  • 30

2 Answers2

7

This is the code that worked for me.

DataTable dt = new DataTable();
DataColumn dc = new DataColumn("Column1");
dc.DataType = System.Type.GetType("System.Byte[]");
dt.Columns.Add(dc);
DataRow row = dt.NewRow();
var imageConverter = new ImageConverter();
row["Column1"] = imageConverter.ConvertTo(Properties.Resources._1, System.Type.GetType("System.Byte[]")); 
dt.Rows.Add(row);
this.dataGridView1.DataSource = dt;
CDspace
  • 2,639
  • 18
  • 30
  • 36
Dev
  • 1,146
  • 2
  • 19
  • 30
6

You can use Bitmap or Byte[] as DataType.

DataGridView displays the type name if you have associated the DataColumn with the DataGridViewTextColumn instead of DataGridViewImageColumn. Add a DataGridViewImageColumn and associate the image column in the DataTable to this created column.

If you want to set the DataType as Byte[], when storing the image, you have to covert the image to Byte[] and while reading from the DataTable covert from Byte[] to image.

dataColumn.DataType = System.Type.GetType("System.Byte[]");

Image to Byte[] conversion

Image image = dataGridView1.Rows[rowIndex].Cells[columnIndex].Value as Image;
if(image != null)
{
    MemoryStream ms = new MemoryStream();
    image.Save(ms, System.Drawing.Imaging.ImageFormat.);
    byte[] imagedata = ms.ToArray();
}

Byte[] to image conversion

MemoryStream ms = new MemoryStream(imagedata);
Image img = Image.FromStream(ms);
dataGridView1.Rows[rowIndex].Cells[columnIndex].Value = img;
Junaith
  • 3,298
  • 24
  • 34