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

如何在WinForm的DataGridView中切换单元格时修改当前单元格背景色?

解决WinForm DataGridView当前单元格高亮问题(FullRowSelection模式)

核心思路

利用CurrentCellChanged事件追踪单元格切换动作,先重置上一个单元格的默认样式,再给当前激活的单元格设置自定义背景色,同时兼容FullRowSelection的整行选中逻辑。

具体实现步骤

1. 记录上一个选中单元格

在Form类里声明全局变量,保存上一次的当前单元格:

private DataGridViewCell _lastCurrentCell;

2. 绑定CurrentCellChanged事件

在窗体构造函数或DataGridView初始化代码里绑定事件:

public YourFormName()
{
    InitializeComponent();
    dataGridView1.CurrentCellChanged += DataGridView1_CurrentCellChanged;
}

3. 编写事件处理逻辑

在事件方法里完成样式重置与当前单元格高亮:

private void DataGridView1_CurrentCellChanged(object sender, EventArgs e)
{
    // 重置上一个单元格的样式为默认
    if (_lastCurrentCell != null)
    {
        _lastCurrentCell.Style.ApplyStyle(dataGridView1.DefaultCellStyle);
    }

    // 给当前单元格设置自定义背景色
    if (dataGridView1.CurrentCell != null)
    {
        dataGridView1.CurrentCell.Style.BackColor = Color.LightSkyBlue; // 替换成你需要的颜色
        dataGridView1.CurrentCell.Style.ForeColor = Color.Black; // 可选:调整文字颜色
        _lastCurrentCell = dataGridView1.CurrentCell;
    }
}

4. 初始加载时高亮默认单元格(可选)

如果需要窗体启动就高亮初始单元格,在Form_Load事件里补充:

private void YourFormName_Load(object sender, EventArgs e)
{
    if (dataGridView1.CurrentCell != null)
    {
        dataGridView1.CurrentCell.Style.BackColor = Color.LightSkyBlue;
        _lastCurrentCell = dataGridView1.CurrentCell;
    }
}

注意事项

  • 颜色可自行替换,比如用Color.FromArgb(255, 245, 250, 255)这类自定义RGB值
  • 若样式不生效,检查DataGridView的EnableHeadersVisualStyles是否设为false,避免系统样式覆盖自定义设置
  • FullRowSelection模式下整行仍会保留默认选中样式,当前单元格会叠加自定义背景色,实现你要的导航高亮效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:42:05