如何在C# Windows Form中点击DataGrid时为PictureBox加载图片
实现DataGrid点击单元格显示对应车型图片到PictureBox
下面分两种常见的数据库图片存储场景给出实现代码:
场景1:数据库存储图片本地/网络路径
如果你的SQL数据库中存储的是图片的文件路径(比如C:\CarImages\Toyota.jpg或http://xxx.com/car.jpg),可以按以下步骤实现:
- 确保你的DataGridView已经绑定了包含图片路径列的数据源(比如DataTable),列名假设为
ImagePath。 - 给DataGridView注册
CellClick事件:
// 在窗体的Load事件或构造函数中添加 dataGridView1.CellClick += DataGridView1_CellClick;
- 编写事件处理方法:
private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { // 排除点击表头的情况 if (e.RowIndex < 0) return; DataGridViewRow selectedRow = dataGridView1.Rows[e.RowIndex]; string imagePath = selectedRow.Cells["ImagePath"].Value?.ToString(); if (string.IsNullOrWhiteSpace(imagePath)) { pictureBox1.Image = null; return; } try { if (imagePath.StartsWith("http://") || imagePath.StartsWith("https://")) { // 加载网络图片 using (var webClient = new System.Net.WebClient()) { byte[] imageBytes = webClient.DownloadData(imagePath); using (var ms = new System.IO.MemoryStream(imageBytes)) { pictureBox1.Image = Image.FromStream(ms); } } } else { // 加载本地图片 pictureBox1.Image = Image.FromFile(imagePath); } // 设置图片自适应模式 pictureBox1.SizeMode = PictureBoxSizeMode.Zoom; } catch (Exception ex) { pictureBox1.Image = null; MessageBox.Show($"图片加载失败:{ex.Message}"); } }
场景2:数据库存储图片二进制数据(BLOB)
如果SQL数据库中直接存储的是图片的二进制字节流(比如用VARBINARY(MAX)类型列存储,列名假设为ImageData),实现代码如下:
- 确保DataGridView绑定了包含
ImageData列的数据源。 - 注册
CellClick事件(同场景1)。 - 编写事件处理方法:
private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex < 0) return; DataGridViewRow selectedRow = dataGridView1.Rows[e.RowIndex]; byte[] imageBytes = selectedRow.Cells["ImageData"].Value as byte[]; if (imageBytes == null || imageBytes.Length == 0) { pictureBox1.Image = null; return; } try { using (var ms = new System.IO.MemoryStream(imageBytes)) { pictureBox1.Image = Image.FromStream(ms); pictureBox1.SizeMode = PictureBoxSizeMode.Zoom; } } catch (Exception ex) { pictureBox1.Image = null; MessageBox.Show($"图片加载失败:{ex.Message}"); } }
注意事项
- 替换代码中的
ImagePath和ImageData为你实际的数据库列名,确保和DataGridView中的列名一致。 - 加载本地图片时,要保证程序有对应路径的读取权限。
- 可以根据需求设置PictureBox的
SizeMode属性,比如StretchImage、AutoSize等。
内容的提问来源于stack exchange,提问作者tVahee
相关产品推荐
相关产品推荐

