簡單專案:就一個 Form
Layout:左邊一個 DataGridView、右邊是 PictureBox
C# Code
using System.IO;
namespace dgvImageColumn2PictureBox
{
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.DataSource = GetDataSource();
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
{
DataPropertyName = "ID",
Name = "ColID",
HeaderText = "編號",
AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader,
Visible = true
});
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
{
DataPropertyName = "Photo",
Name = "ColPhoto",
HeaderText = "字串路徑",
Width = 100,
Visible = true
});
// UseColumnTextForButtonValue = true 才會顯示 Text 設定文字喔
dataGridView1.Columns.Add(new DataGridViewButtonColumn
{
Name = "ColBtn",
HeaderText = "檢視完整圖片",
Text = "檢視完整圖片",
Width = 100,
Visible = true,
UseColumnTextForButtonValue = true
});
dataGridView1.CellContentClick += DataGridView1_CellContentClick;
pictureBox1.MouseLeave += PictureBox1_MouseLeave;
// 預設 PictureBox 是隱藏的
HidePhoto();
}
private void PictureBox1_MouseLeave(object sender, EventArgs e)
{
HidePhoto();
}
private void ShowPhoto(string PhotoPath)
{
using (FileStream fs = new FileStream(PhotoPath, FileMode.Open, FileAccess.Read))
{
pictureBox1.Image = Image.FromStream(fs);
pictureBox1.Visible = true;
pictureBox1.BringToFront();
pictureBox1.Focus();
// 設定 PictureBox 的位置。
pictureBox1.Location = new Point
(
PointToClient(MousePosition).X,
PointToClient(MousePosition).Y
);
}
}
private void HidePhoto()
{
pictureBox1.Visible = false;
pictureBox1.SendToBack();
}
private void DataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0) return;
if ((sender is DataGridView) == false) return;
DataGridView dgv = sender as DataGridView;
if (e.ColumnIndex != dgv.Columns["ColBtn"].Index) return;
string PhotoPath = dgv.Rows[e.RowIndex].Cells["ColPhoto"].Value.ToString();
ShowPhoto(PhotoPath);
}
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\Image1.JPG");
dt.Rows.Add(2, @"D:\Image\Image2.JPG");
dt.Rows.Add(3, @"D:\Image\Image3.JPG");
dt.Rows.Add(4, @"D:\Image\Image4.JPG");
dt.Rows.Add(5, @"D:\Image\Image5.JPG");
return dt;
}
}
}
沒有留言:
張貼留言