Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
791 views
in Technique[技术] by (71.8m points)

image - Showing a bitmap in dataGridView using C#

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

dataGridview.source = dataTable;

Now, I want to show in dataGridView three columns, two from dataTable and new third with my bitmap. If it is easier, I can modify dataTable and dataGridView.

Is it possible to do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...