利用 DataGridViewImageColumn 來顯示圖片,要在 CellFormatting Event 內,把字串路徑轉換為圖檔,並塞進 Cell 內
簡易專案,就通通寫在一個 Form 內
C# Code
using System.IO;
namespace DGVImageColumn
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.AutoGenerateColumns = false;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.Dock = DockStyle.Fill;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;
dataGridView1.DataSource = GetDataSource();
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
{
DataPropertyName = "ID",
Name = "ColID",
HeaderText = "編號",
AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader,
Visible = true
});
// 設定 DataGridViewImageColumn 欄位
dataGridView1.Columns.Add(new DataGridViewImageColumn
{
DataPropertyName = "Photo",
Name = "ColPhoto",
HeaderText = "相片",
ImageLayout = DataGridViewImageCellLayout.Zoom,
Visible = true
});
dataGridView1.CellFormatting += DataGridView1_CellFormatting;
}
private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// 點選 CellHeader 就不往下跑
if (e.RowIndex == -1) return;
// 確定資料是 string
if ((e.Value is string) == false) return;
// 把 Sender 轉回 DataGridView
if ((sender is DataGridView) == false) return;
DataGridView dgv = sender as DataGridView;
// 是 Photo 欄位才往下跑
if (e.ColumnIndex != dgv.Columns["ColPhoto"].Index) return;
string PhotoPath = e.Value.ToString();
// 滑鼠移到該 Cell 會顯示該圖片路徑
DataGridViewCell cell = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex];
cell.ToolTipText = PhotoPath;
// Stream 都用 using 包起來,確定會 Dispose
using (FileStream fs =
new FileStream(
PhotoPath,
FileMode.Open,
FileAccess.Read))
{
e.Value = Image.FromStream(fs);
}
}
private DataTable GetDataSource()
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Photo", typeof(string));
dt.Rows.Add(1, @"D:\Image\dgvImage1.jpg");
dt.Rows.Add(2, @"D:\Image\dgvImage2.jpg");
dt.Rows.Add(3, @"D:\Image\dgvImage3.jpg");
dt.Rows.Add(4, @"D:\Image\dgvImage4.jpg");
dt.Rows.Add(5, @"D:\Image\dgvImage5.jpg");
return dt;
}
}
}
結果在 CellFormatting 內直接指定 e.value = 字串路徑的話,會出現下面的錯誤訊息,DataGridViewImageColumn 上都會是叉燒包
沒有留言:
張貼留言