Showing a bitmap in dataGridView using C#

后端 未结 2 904
后悔当初
后悔当初 2020-12-19 17:20

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

dataGridview.source = d         


        
相关标签:
2条回答
  • 2020-12-19 18:17

    There are several ways you can approach this.

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

    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 needed.

    The example above plus a whole lot of other discussion can be found on MSDN.


    Another option is to add your image into the datatable - this will automatically generate your image column, but the new column in the datatable needs to be of type byte array.

    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 do take this approach I'd suggest doing a little research to find the best method of creating the byte array - I couldn't vouch for that code being the best.

    0 讨论(0)
  • 2020-12-19 18:21

    Simply create datatable with image column and add image to it

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

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

    0 讨论(0)
提交回复
热议问题