C# WinForms中DataGridView选中行/单元格时PictureBox不更新问题
解决方案
1. 切换到更可靠的触发事件
CellStateChanged会在单元格状态(如选中、编辑)变化时频繁触发,容易导致逻辑混乱。建议改用SelectionChanged事件,仅在选中内容变更时执行更新:
private void dgv1_SelectionChanged(object sender, EventArgs e) { // 无选中行时直接返回,避免空引用错误 if (dgv1.CurrentRow == null) return; // 安全获取单元格值,避免空值报错 string setcode = dgv1.CurrentRow.Cells[1].Value?.ToString() ?? string.Empty; string cardname = dgv1.CurrentRow.Cells[5].Value?.ToString() ?? string.Empty; if (string.IsNullOrEmpty(setcode) || string.IsNullOrEmpty(cardname)) { pictureBox1.Image = null; return; } string imgpath = Path.Combine(Environment.CurrentDirectory, "pics", setcode, cardname + ".full.jpg"); // 检查文件是否存在 if (!File.Exists(imgpath)) { pictureBox1.Image = null; return; } // 安全更新图片 pictureBox1.Image?.Dispose(); pictureBox1.Image = Image.FromFile(imgpath); pictureBox1.Invalidate(); // 强制控件重绘 }
2. 验证路径与图片加载逻辑
- 加断点或用
Console.WriteLine输出setcode、cardname、imgpath的值,确认选中不同行时这些值确实在变化。 - 若需要避免
Image.FromFile锁定图片文件,改用流加载方式:
using (var fs = new FileStream(imgpath, FileMode.Open, FileAccess.Read)) { pictureBox1.Image?.Dispose(); pictureBox1.Image = Image.FromStream(fs); }
3. 确保UI线程更新控件
如果你的图片更新逻辑在后台线程执行,必须通过Invoke切换到UI线程操作控件:
private void UpdatePicture(string imgPath) { if (pictureBox1.InvokeRequired) { pictureBox1.Invoke(new Action<string>(UpdatePicture), imgPath); return; } pictureBox1.Image?.Dispose(); pictureBox1.Image = Image.FromFile(imgPath); pictureBox1.Invalidate(); }
内容的提问来源于stack exchange,提问作者AndyDingoWolf
相关产品推荐
相关产品推荐

