双击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
相关产品推荐
相关产品推荐

