You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 01:20:46