Displaying a bitmap in a dataGridView using C #

I want to show some image in dataGridView. I have two components: dataGridView, dataTable and one Bitmap. DataTable has two columns.

dataGridview.source = dataTable; 

Now I want to show three columns in the dataGridView, two from dataTable and a new third with my bitmap. If it's easier, I can change the dataTable and dataGridView.

Can this be done?

+4
source share
2 answers

There are several ways to approach this.

There is an image column type for a DataGridView, DataGridViewImageColumn, which has an image property with which you can pass a bitmap image.

Something like the following should work:

 private void createGraphicsColumn(Bitmap image) { DataGridViewImageColumn imageColumn = new DataGridViewImageColumn(); imageColumn.Image = image; imageColumn.Name = "Tree"; imageColumn.HeaderText = "Nice tree"; dataGridView1.Columns.Insert(2, imageColumn); } 

You can also set the Value property of individual cells in this column, if necessary.

The example above and a host of other discussions can be found on MSDN .


Another option is to add your image to the datatable - this will automatically generate your image column, but the new column in the datatable should have an array of type bytes.

I found the following code to do this with a quick google:

 public byte[] imageToByteArray(System.Drawing.Image imageIn) { MemoryStream ms = new MemoryStream(); imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif); return ms.ToArray(); } 

If you take this approach, I would suggest doing a little research to find the best way to create a byte array - I could not vouch for the best code.

+3
source

Just create a datatable with an image column and add an image to it

 dtMain.Columns.Add("ImageColumn", typeof(Image)); dtMain.Rows.Add(Image.FromFile(photopath + "1.jpg")); 

Download the full code at http://tablegridview.blogspot.in

+2
source

All Articles