简体   繁体   中英

How to preview images with given path

I have an image path located in my database and I want to show the image with the other table fields in a gridview (I have ID, Name, ImagePath, Date). I have tried to use sqlDataReader but it only shows the Image path. I want it to show the image itself. Can someone please help me how to view all of the images?

If it is a DataGridView you are referring to, you may have noticed that a Column ValueType can be set to DataGridViewImageColumn. Once set, that Column Cells will display Bitmaps.

Now, since your (I think) DataSource is giving you the Path to an Image file, you may assign that string Value to the Cells of a hidden Column.

When the Value of that hidden Cell is changed by the DataSource (or whatever else), you use it to load the image it points to.

Here I suppose that the Column set to DataGridViewImageColumn is Column[1] and the hidden Column is Column[0]:

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
   if ((e.ColumnIndex == 0) & (e.RowIndex >= 0))
   {
      string sFileName = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
      using (Bitmap _bitmap = new Bitmap(sFileName, true))
      {
         this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 1].Value = new Bitmap(_bitmap);
      }
   }

}

It's a good idea not to use the Image File directly to load the Bitmap, because GDI++ will lock that image file on disk. So I use a Bitmap copy of the Image and pass that to the Cell Value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM