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

双击DataGridViewImageColumn切换图片与Tooltip无效果问题求助

问题分析与解决方案

核心问题

你的代码存在两个关键错误,导致双击后图标和Tooltip无变化:

  • 滥用using语句:DataGridViewRow和DataGridViewCell是DataGridView的内部控件实例,不能用using包裹——using会在代码块结束后自动销毁这些对象,你的修改根本无法同步到UI上。
  • Tooltip设置对象错误:你需要修改的是可见的ProjectLocked图片列的Tooltip,但代码里却给隐藏的DeleteLock列设置了Tooltip,自然看不到变化。

修正后的代码

private void dgvProjectLocks_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    // 跳过表头行
    if (e.RowIndex < 0) return;
    
    var dgv = (DataGridView)sender;
    // 仅处理ProjectLocked列的双击事件
    if (dgv.Columns[e.ColumnIndex].Name != "ProjectLocked") return;

    var currentRow = dgv.Rows[e.RowIndex];
    var deleteCell = currentRow.Cells["DeleteLock"];
    bool isChecked = Convert.ToBoolean(deleteCell.Value);

    if (isChecked)
    {
        // 切换为锁定状态
        currentRow.DefaultCellStyle.BackColor = dgv.DefaultCellStyle.BackColor;
        currentRow.DefaultCellStyle.ForeColor = dgv.DefaultCellStyle.ForeColor;
        deleteCell.Value = false;
        currentRow.Cells["ProjectLocked"].Value = Resources.locked;
        // 设置图片列的Tooltip
        currentRow.Cells["ProjectLocked"].ToolTipText = Resources.AddProjectLockDeleteToolTip;
    }
    else
    {
        // 切换为解锁状态
        currentRow.DefaultCellStyle.BackColor = Color.LightGray;
        currentRow.DefaultCellStyle.ForeColor = Color.DarkGray;
        deleteCell.Value = true;
        currentRow.Cells["ProjectLocked"].Value = Resources.unlocked;
        // 设置图片列的Tooltip
        currentRow.Cells["ProjectLocked"].ToolTipText = Resources.RemoveProjectLockDeleteToolTip;
    }

    // 手动刷新行,确保UI立即更新
    currentRow.Refresh();
}

额外注意事项

  • 确保Resources.locked和Resources.unlocked是有效的Bitmap对象,未被提前销毁,否则图片无法正常显示。
  • 若修改后UI仍有更新延迟,可尝试调用dgv.Refresh()强制刷新整个DataGridView,但优先使用行刷新更高效。

内容的提问来源于stack exchange,提问作者MartinS

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 16:55:15